【python基础】python中常用字符串函数详解

1 字符串查询(index,find)

建议使用find,因为如果没有找到匹配的字符串,index方法会报异常。

方法名称功能
find(str, beg=0, end=len(string))查找子串str第一次出现的位置,如果找到则返回相应的索引,否则返回-1
rfind(str, beg=0,end=len(string))类似于 find()函数,不过是从右边开始查找
index(str, beg=0, end=len(string))类似于find,只不过如果没找到会报异常。
rindex(str, beg=0 end=len(string))类似于rfind,如果没有匹配的字符串会报异常

代码举例

str1 = "my name is qlee,what your name?"
str2 = "name"

print(str1.find(str2))#全部查找
print(str1.find(str2,5))#从第5个元素开始查找
print(str1.find(str2,35))# 从第35个元素开始查找,超过元素索引或者没找到,不会报错

输出:

3
26
-1

2. 字符串大小写转换操作(upper、lower、swapcase、capitalize和title)

方法名称功能
upper将字符串中所有元素都转为大写
lower将字符串中所有元素都转为小写
swapcase交换大小写。大写转为小写,小写转为大写
capitalize第一个大写,其余小写
title每个单词的第一次字符大写,其余均为小写

代码举例:

txt = "my name is Qlee"
print(txt.upper())
print(txt.lower())
print(txt.swapcase())
print(txt.capitalize())
print(txt.title())

输出:

MY NAME IS QLEE
my name is qlee
MY NAME IS qLEE
My name is qlee
My Name Is Qlee

3. 字符串对齐(center,just和zfill)

方法名称功能
center(width, fillchar)返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
ljust(width[, fillchar])返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
rjust(width,[, fillchar])返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
zfill (width)返回长度为 width 的字符串,原字符串右对齐,前面填充0

代码举例:

str = "hello world!"
print (str.center(30, '*'))
print (str.ljust(30, '*'))
print (str.rjust(30, '*'))
print (str.zfill(30))

输出:

*********hello world!*********
hello world!******************
******************hello world!
000000000000000000hello world!

4. 分割字符串(split、splitlines和partition)

方法名称功能
split(seq=“”, num=string.count(str))以 seq (默认空格)为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串(只需num个seq分隔符)。分割后得到新列表
rsplit与split类似,不过是从右边开始分割
splitlines按照行进行分割,得到新的列表
partition(str)找到字符串中第一个str,并以str为界,将字符串分割为3部分,返回一个新的元组
rpartition(str)与partition类似,只不过是反向找

代码举例:

str = "my name is qlee, what is your name"
print(str.split())       # 以空格为分隔符
print(str.split('i',1))   # 以 i 为分隔符
print(str.split('b'))     # 以b为分隔符,没找到不会报错
print(str.partition("name"))#找到第一个name,分割为三部分
print(str.rpartition("name"))#反向找到第一个name,分割为三部分

str = """my name is qlee
      what is your name"""
print(str.splitlines())

输出:

['my', 'name', 'is', 'qlee,', 'what', 'is', 'your', 'name']
['my name ', 's qlee, what is your name']
['my name is qlee, what is your name']
('my ', 'name', ' is qlee, what is your name')
('my name is qlee, what is your ', 'name', '')
['my name is qlee', '      what is your name']

5. 合并与替换(join,replace)

方法名称功能
join(seq)以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
replace(old, new [, max])把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次

代码举例:

print("----------join-----------")
seq1 = ("h", "e", "l", "l", "o") #元组
seq2 = ["h", "e", "l", "l", "o"] #列表
seq3 = "hello" #字符串
print ("".join(seq1)) #无分隔符
print (" ".join(seq1))#空格
print (",".join(seq1))#","

print("----------replace-----------")
str1 = "my name is qlee"
print (str1.replace("qlee", "lq")) #注意str1本身不发生改变

输出:

----------join-----------
hello
h e l l o
h,e,l,l,o
----------replace-----------
my name is lq

6. 判断字符串(isidentifier、isspace、isalpha、isdecimal、isnumeric和isalnum等)

方法名称功能
isidentifier判断字符串是不是合法标识符(字符、数字、下划线)
isspace判断字符是否只有空白字符(回车、换行和水平制表符)
isalpha判断字符串是否全部由字母组成
isdecimal判断字符是否全部由十进制的数字组成,不包括中文、罗马字符
isdigit判断字符串只包含数字,不包括中文数字
isnumeric判断字符串是否全部由数字组成,中文数字也算
isalnum判断字符串是否由字母和数字组成
islower判断字符串中的字符是否全部为小写,字符串至少有一个字符
isupper判断字符串中的字符是否全部为大写,字符串至少有一个字符
istitle判断字符串是否标题话,见titile
isascii如果字符串为空或字符串中的所有字符都是 ASCII,则返回 True,否则返回 False。
isprintable如果所有字符都是可打印的,则 isprintable() 方法返回 True,否则返回 False。

举例说明:

print("hello&".isidentifier())#False,&为非法标识符
print("   t".isspace())#False,"t"为非空
print("aldflafd你好".isalpha())#ture,中文也可以
print("123四".isdecimal())#False,中文不属于十进制
print("123四".isnumeric())#True,中文、罗马字符的数字也算
print("123abc".isalnum())#True,只能字母和数字
print("123四".isdigit())#False,不能包括中文
print("".islower())# False,不能为空字符
print("TLUHBH".isupper())#True
print("My Name Is Qlee".istitle())#True,只有第一个字符为大写
print("我是中国人".isascii())#False,中文不属于ascii
print("Hello!\nAre you ?".isprintable()) #False,\n不可打印

7. 字符串的比较(<,>,max,min等)

字符串的比较操作:

方法名称功能
max(str)返回字符串 str 中最大的字母
min(str)返回字符串 str 中最小的字母
ord将指定字符转换为原始值
chr将原始值转换为对应的字符

举例说明:

str = "mynameisqlee"
print("max(str): ", max(str),"min(str): ", min(str))
print("hello" < "Hello")
print(ord("c"))
print(chr(98))

输出:

max(str):  y min(str):  a
False
99
b

8. 去除两端多余字符操作(strip)

方法名称功能
lstrip(str)去掉左边的str字符(不是字符串),默认为空白字符
rstrip(str)去掉右边的str字符
strip(str)去掉左右两边的str字符

代码举例:

str = "   my name is qleeeeee"
print(str.strip()) #去掉两边的空白
print(str.rstrip("e")) #去掉右边的"e"字符
str = "!!!!my name is qlee!!!!"
print(str.strip("!")) #去掉左右边的"!"字符

输出:

my name is qleeeeee
   my name is ql
my name is qlee

9. 判断开头结尾字符串(startswith,endswith)

方法名称功能
startswith(str)检查字符串是否以str开头,若是则返回true
endswith(str)检查字符串是否以str结尾,若是则返回true

代码距离:

str = "my name is qlee"
print(str.startswith("my"))#True
print(str.endswith("is"))#False

10. 字符串计数(count,len)

方法名称功能
count(sub, start= 0,end=len(string))在字符串[start,end)范围内,计算sub字符串的个数
lenlen不是string的方法,是内置函数,计算字符串中的字符个数

代码举例:

str = "my name is qlee, what is your name?"
print(str.count("name")) #2
print(len(str))# 35

11. 字符串的编码与解码(encode,decode)

方法名称功能
encode(encoding=‘UTF-8’,errors=‘strict’)以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是’ignore’或者’replace’
bytes.decode(encoding=“utf-8”, errors=“strict”)Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回

代码举例:

str = "我是中国人"
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")

print("原字符串:",str)
print("------------编码---------------")
print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)
print("------------解码---------------")
print("UTF-8 解码:", str_utf8.decode('UTF-8', 'strict'))
print("GBK 解码:", str_gbk.decode('GBK', 'strict'))

输出:

原字符串: 我是中国人
------------编码---------------
UTF-8 编码: b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba'
GBK 编码: b'\xce\xd2\xca\xc7\xd6\xd0\xb9\xfa\xc8\xcb'
------------解码---------------
UTF-8 解码: 我是中国人
GBK 解码: 我是中国人

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年3月11日
下一篇 2023年3月11日

相关推荐