目录
字母转小写(适用于在国际化环境中,忽略字母大小写进行比较的场景)
字母转小写(适用于非国际化环境中,忽略字母大小写进行比较的场景)
检查字符串中的所有字符是否都是可打印字符,或者字符串是否为空。
检查字符串中的所有字符是否都是空白字符,并且至少包含一个字符。
掌握字符串类型的使用方法。本文参考官方文档列举了各种字符串方法的使用方法,如有错误烦请指正。
Python 3.12.0
Text Sequence Type — str
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
官方定义:
Single quotes:
'allows embedded "double" quotes'Double quotes:
"allows embedded 'single' quotes"Triple quoted:
'''Three single quotes''',"""Three double quotes"""
译文:
- 单引号:单引号可以嵌入双引号,例如:'I "LOVE" YOU'
- 双引号:双引号可以嵌入单引号,例如:"I 'LOVE' YOU"
- 三个单引号:例如:'''I LOVE YOU'''
- 三个双引号:例如:"""I LOVE YOU"""
案例:
- print('I "LOVE" YOU')
- print("I 'LOVE' YOU")
- print('''I LOVE YOU''')
- print("""I LOVE YOU""")
注意:
Python中,三个引号有两个作用:
- '''
- 输出:
- I
- LOVE
- YOU
- '''
- print('''I
- LOVE
- YOU
- ''')
-
- """
- 输出:
- I
- LOVE
- YOU
- """
- print("""I
- LOVE
- YOU
- """)
情景一
字符串之间只有空格,则会隐式地转换为单个字符串。
案例
- a="123" "456"
- b="123456"
- #返回:True 1805713063440 1805713063440
- print(a==b,id(a),id(b))
情景二
字符串用+连接。
案例
- a="123456"
- b="123"+"456"
- #返回:True 2281180461648 2281180461648
- print(a==b,id(a),id(b))
情景三
用%s连接。
- a = "123"
- b = "456"
- #返回:123456
- result = "%s%s" % (a, b)
- print(result)
情景四
用{}连接。
- a = "123"
- b = "456"
- #返回:123456
- result = "{}{}".format(a,b)
- print(result)
情景五
在字符串前加f引用变量。
- a = "123"
- b = "456"
- #返回:123456
- result = f"{a}{b}"
- print(result)
情景六
使用join方法将列表中的元素拼接成一个字符串。
- a = ["123","456"]
- result = "".join(a)
- #返回:123456
- print(result,type(result))
转换后的字符串是一个新的字符串。从下面案例中的id值可以看出。
案例
- #输出:I love you.
- print("I LOVE YOU.".capitalize())
- #输出:I love you.
- print("i love you.".capitalize())
-
- a="I love you."
- b=a.capitalize()
- #输出:I love you. I love you. 2532951714032 2532951257840
- print(a,b,id(a),id(b))
该方法的实现遵循Unicode标准中描述的大小写折叠算法。可以将特殊字符转换为小写形式,比lower()函数更为彻底。
案例
- a="I LOVE YOU.".casefold()
- b="I love you.".casefold()
- #输出:i love you. i love you. True 2692128699120 2692128698480
- print(a,b,a==b,id(a),id(b))
-
- c="ß".casefold()
- d="ss"
- #输出:True
- print(c==d)
案例
- a="I LOVE YOU."
- #输出:i love you.
- print(a.lower())
案例
- a="i love you."
- #输出:I LOVE YOU.
- print(a.upper())
案例
- a = "Hello world!"
- #输出:hELLO WORLD!
- print(a.swapcase())
center(width,fillchar)函数有两个参数。它的作用是:将原始字符串居中放置在长度为width的字符串中,并使用字符fillchar进行填充。fillchar默认为空格。如果原字符串长度大于或等于width,则没有fillchar进行填充。
案例
- a="123".center(10)
- #输出: 123 长度: 10
- print(a,"长度:",len(a))
- #输出:---123---- 长度: 10
- b="123".center(10,"-")
- print(b,"长度:",len(b))
类比center函数。
案例
- a="123".ljust(10)
- #输出:123 长度: 10
- print(a,"长度:",len(a))
- #输出:123------- 长度: 10
- b="123".ljust(10,"-")
- print(b,"长度:",len(b))
类比center函数。
案例
- a="123".rjust(10)
- #输出: 123 长度: 10
- print(a,"长度:",len(a))
- #输出:-------123 长度: 10
- b="123".rjust(10,"-")
- print(b,"长度:",len(b))
案例
- a = "1"
- #输出:00001
- print(a.zfill(5),type(a.zfill(5)))
-
- b = "-9"
- #输出:-0009
- print(b.zfill(5),type(b.zfill(5)))
-
- c= "hello"
- #输出:000hello
- print(c.zfill(8),type(c.zfill(8)))
-
- #输出:hello
- print(c.zfill(2),type(c.zfill(2)))
案例
- a="I LOVE YOU."
- #输出:1
- #分析:在I LOV中寻找LOV,看一共出现了几次。
- print(a.count("LOV",0,5))
-
- b="1111"
- #输出:2
- #分析:在1111中寻找11出现的次数。特别注意,这个函数不会重叠计算,所以中间两个1不会统计。
- print(b.count("11",0, len(b)))
案例
- a="你好,世界!"
- #将字符串编码为字节序列(默认使用UTF-8编码)
- by = a.encode()
- #输出:b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
- print(by,type(by))
-
- #指定编码方式为'UTF-8',将字符串编码为字节序列
- by2 = a.encode(encoding='UTF-8')
- #输出:b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
- print(by2,type(by2))
案例
- a="123"
- #输出:True
- print(a.endswith("23"))
案例
- a="123"
- #输出:False
- print(a.startswith("23"))
案例
- a= "hello\tworld.\nhello\rPython."
- '''
- 分析:\t表示制表符;\n表示换行符;\r表示回车符。回车符会使得前一个元素消失。所以第二个hello没有打印出来。
- 输出:
- hello world.
- Python.
- '''
- print(a.expandtabs())
-
- b= "hello\tworld"
- #输出:hello world
- #分析:一个制表符用16个空格代替。
- print(b.expandtabs(tabsize=16))
案例一(从左边开始寻找)
调用find函数查找子字符串,找不到会返回-1。
- index = "hello python".find("python")
- #输出:6
- #分析:下标从0开始寻找,python在字符串的第7位
- print(index)
-
- index2 = "hello python python".find("python",7,64)
- #输出:13
- #分析:下标从7开始寻找,python在字符串的第13位
- print(index2)
-
- index = "hello python".find("world")
- #输出:-1
- #分析:字符串不包含world
- print(index)
案例二(从右边开始寻找)
- index = "hello python".rfind("python")
- #输出:6
- #分析:python在字符串的第7位出现。
- print(index)
-
- index2 = "hello python python python".rfind("python",0,15)
- #输出:6
- #分析:在0至15之间寻找python,python在字符串的第6位出现。
- print(index2)
-
- index = "hello python".rfind("world")
- #输出:-1
- #分析:字符串不包含world
- print(index)
案例三(从左边开始寻找)
调用index函数查找子字符串,找不到会报错。
- a = "hello world world world world"
- #输出:索引位置: 6
- print("索引位置:", a.index("world"))
- #输出:索引位置: 18
- #分析:从第15位开始寻找,第一次出现world的位置是19位。
- print("索引位置:", a.index("world",15))
- #输出:索引位置: 24
- #分析:从第19位开始寻找,第一次出现world的位置是25位。
- print("索引位置:", a.index("world",19, len(a)))
-
- b = "hello world"
- try:
- index = b.index("Python")
- print("索引位置:", index)
- except ValueError as e:
- #输出:未找到子串: substring not found
- print("未找到子串:", e)
案例四(从右边开始寻找)
调用rindex函数查找子字符串,找不到会报错。
- a = "hello world world world world"
- #输出:索引位置: 24
- print("索引位置:", a.rindex("world"))
- #输出:索引位置: 24
- print("索引位置:", a.rindex("world",15))
- #输出:索引位置: 12
- print("索引位置:", a.rindex("world",5,19))
-
- b = "hello world"
- try:
- index = b.rindex("Python")
- print("索引位置:", index)
- except ValueError as e:
- #输出:未找到子串: substring not found
- print("未找到子串:", e)
案例
- a = "I love you {} times {} day."
- b=a.format(3000,"a")
- #输出:I love you 3000 times a day.
- print(b)
案例
- #定义一个字典子类作为映射
- class Student(dict):
- def __missing__(self, key):
- return f"Key {key} not found"
-
- #创建一个字典子类的实例
- mapping = Student({'name': 'zhangsan', 'age': 30})
- template = "I am {name} , I am {age} years old, I LOVE {obj}."
- #格式化
- formatted_string = template.format_map(mapping)
- #输出:I am zhangsan , I am 30 years old, I LOVE Key obj not found.
- print(formatted_string)
案例
- a = "abc"
- b="I LOVE YOU."
- c="123"
- d=""
- #输出:True False True False
- #b含有空格和.所以返回False
- #d不符合至少有一个字符的条件,所以返回False
- print(a.isalnum(),b.isalnum(),c.isalnum(),d.isalnum())
案例
- a = "abc"
- b="I LOVE YOU."
- c="123"
- d=""
- #输出:True False False False
- #b含有空格和.所以返回False
- #c不是字母组成的字符串。
- #d不符合至少有一个字符的条件,所以返回False
- print(a.isalpha(),b.isalpha(),c.isalpha(),d.isalpha())
案例
- a = "Hello World!"
- b = "Hello世界!"
- c=""
- #输出:True False
- #分析:a中所有元素由ASCII字符组成。b字符串中不全是ASCII表中的字符,所以返回False。当字符串为空字符串时,该方法也返回True。
- print(a.isascii(),b.isascii(),c.isascii())
案例
- a = "Hello World!"
- b = "3.14"
- c="10086"
- d=""
- #输出:False False True False
- print(a.isdecimal(),b.isdecimal(),c.isdecimal(),d.isdecimal())
案例
- a = "Hello World!"
- b = "3.14"
- c="10086"
- d=""
- #输出:False False True False
- print(a.isdigit(),b.isdigit(),c.isdigit(),d.isdigit())
注意
案例
- a = "Hello World!"
- b = "hi"
- c="a,b,c"
- d="www.hao123.com"
- e=""
- f="123"
- #输出:False True True True False False
- print(a.islower(),b.islower(),c.islower(),d.islower(),e.islower(),f.islower())
包括:普通数字字符和具有Unicode数值属性的所有字符。
案例
- a = "Hello World!"
- b = "123"
- c="3.14"
- d="-1"
- e=""
- #输出:False True False False False
- print(a.isnumeric(),b.isnumeric(),c.isnumeric(),d.isnumeric(),e.isnumeric())
- a = "Hello \n World!"
- b = "123\t"
- c="3.14\r"
- d="-1"
- e=""
- #输出:False False False True True
- print(a.isprintable(),b.isprintable(),c.isprintable(),d.isprintable(),e.isprintable())
案例
- a = "Hello World!"
- b = " "
- c="\t"
- d="\n"
- e=""
- #输出:False True True True False
- print(a.isspace(),b.isspace(),c.isspace(),d.isspace(),e.isspace())
案例
- a = "hello world"
- b = a.title()
- #输出: Hello World
- print(b)
标题格式
案例
- a = "Hello World!"
- b = "Hello \n World!"
- c="USA"
- d=""
- #输出:True True False False
- print(a.istitle(),b.istitle(),c.istitle(),d.istitle())
注意
案例
- a = "Hello World!"
- b = "HI"
- c="C,B,A"
- d="www.hao123.com"
- e=""
- f="123"
- #输出:False True True False False False
- print(a.isupper(),b.isupper(),c.isupper(),d.isupper(),e.isupper(),f.isupper())
注意:如果可迭代对象中的元素包含非字符串,则程序报错。
案例
- a = ["I", "LOVE", "Python"]
- b="\t".join(a)
- #输出:I LOVE Python
- print(b,type(b))
案例
- a=" hello world. "
- #输出:hello world.
- print(a.strip())
-
- b=" hello world. "
- #输出:ello world
- print(b.strip(" h.l"))
案例
- a=" 1 2 3 "
- b=" I LOVE YOU . "
- #输出:LOVE YOU .
- c=b.lstrip(" I")
- print(c)
- #输出:1 2 3
- d=a.lstrip(" ")
- print(d)
- #输出:1 2 3
- e=a.lstrip()
- print(e)
案例
- a=" 1 2 3 "
- b=" I LOVE YOU . "
- #输出: I LOVE YOU
- c=b.rstrip(". ")
- print(c)
- #输出: 1 2 3
- d=a.rstrip(" ")
- print(d)
- #输出: 1 2 3
- e=a.rstrip()
- print(e)
案例
- #创建翻译表,将数字转换为对应的中文数字
- translationTable = str.maketrans("0123456789", "零一二三四五六七八九")
-
- #使用翻译表进行转换
- a = "996"
- b = a.translate(translationTable)
- #输出:九九六
- print(b)
-
- #创建翻译表,将小写字母转换为大写字母
- translationTable = str.maketrans("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
-
- #使用翻译表进行转换
- word = "i love you."
- capitalizedWord = word.translate(translationTable)
- #输出:I LOVE YOU.
- print(capitalizedWord)
返回的元组一共有三个元素,三个元素含义如案例所示。
案例一(从左边开始寻找)
- a="www.hao123.com"
- result=a.partition(".")
-
- """
- 第一个.是在www之后,所以元组的第一个元素是www,第二个元素是.第三个元素是hao123.com
- 可以看到,result的类型是元组类型。
- """
- #输出:('www', '.', 'hao123.com')
- print(result,type(result))
-
-
- result=a.partition("!")
- #输出:('www.hao123.com', '', '')
- print(result,type(result))
案例二(从右边开始寻找)
- a="www.hao123.com"
- result=a.rpartition(".")
- #输出:('www.hao123', '.', 'com')
- print(result,type(result))
-
- result=a.rpartition("!")
- #输出:('', '', 'www.hao123.com')
- print(result,type(result))
案例
- a="##123"
- b=a.removeprefix("##")
- c=a.removeprefix("###")
-
- #输出:##123 1812850244176
- print(a,id(a))
- #输出:123 1812850335424
- #分析:可以看出b是个新字符串。
- print(b,id(b))
- #输出:##123 1812850244176
- #分析:返回原字符串,c不是一个新字符串。
- print(c,id(c))
案例
- a="123##"
- b=a.removesuffix("##")
- c=a.removesuffix("###")
-
- #输出:123## 2665880255056
- print(a,id(a))
- #输出:123 2665880346304
- #分析:可以看出b是个新字符串。
- print(b,id(b))
- #输出:123## 2665880255056
- #分析:返回原字符串,c不是一个新字符串。
- print(c,id(c))
案例
- a="I LOVE JAVA."
- b="I have two apples and two oranges."
- #输出:I LOVE Python.
- c= a.replace("JAVA", "Python")
- print(c)
- #输出:I have three apples and two oranges.
- #分析:第三个参数位1,表示只替换第一次出现的two位three。
- d= b.replace("two", "three",1)
- print(d)
rsplit(sep,maxsplit)从右边开始拆分字符串,split(sep,maxsplit)从左边开始拆分字符串。两个方法都返回包含拆分后的子字符串的列表。它们有两个参数:
案例(这里以rsplit(sep,maxsplit)为例,split(sep,maxsplit)和其不同点在于拆分顺序不同。)
- #默认用空格分隔,默认分隔次数最大。
- #输出:['Dog', 'Cat', 'Elephant', 'Lion', 'Tiger', 'Giraffe', 'Monkey', 'Kangaroo', 'Penguin', 'Dolphin']
- animal = "Dog Cat Elephant Lion Tiger Giraffe Monkey Kangaroo Penguin Dolphin"
- animalList = animal.rsplit()
- print(animalList)
-
- #输出:['Apple', 'Banana', 'Orange', 'Strawberry', 'Mango', 'Pineapple', 'Watermelon', 'Grapes', 'Blueberry', 'Peach']
- fruit = "Apple,Banana,Orange,Strawberry,Mango,Pineapple,Watermelon,Grapes,Blueberry,Peach"
- fruitList = fruit.rsplit(',')
- print( fruitList)
-
- #指定最大拆分次数
- #输出:['Carrot Broccoli Spinach,Tomato Potato Cucumber', 'Onion', 'Cauliflower', 'Peas']
- vegetable = "Carrot Broccoli Spinach,Tomato Potato Cucumber Onion Cauliflower Peas"
- vegetableList = vegetable.rsplit(maxsplit=3)
- print( vegetableList)
-
- #输出:['Emma,Liam,Olivia,Noah,Sophia,Jackson,Ava', 'Lucas', 'Isabella', 'Oliver']
- name = "Emma,Liam,Olivia,Noah,Sophia,Jackson,Ava,Lucas,Isabella,Oliver"
- nameList = name.rsplit(',',maxsplit=3)
- print( nameList)
splitlines(keepends)方法中keepends默认为False,表示返回的列表中不包含分隔符号,设置为True表示包含分隔符。中以下是官方文档规定的符号,注意:在版本3.2中进行了更改,加入了\v和\f
| Representation | Description | 翻译 |
| \n | Line Feed | 换行符 |
| \r | Carriage Return | 回车 |
| \r\n | Carriage Return + Line Feed | 回车+换行 |
| \v or \x0b | Line Tabulation | 行表格 |
| \f or \x0c | Form Feed | 换页 |
| \x1c | File Separator | 文件分隔符 |
| \x1d | Group Separator | 组分隔符 |
| \x1e | Record Separator | 记录分隔符 |
| \x85 | Next Line (C1 Control Code) | 下一行(C1控制代码) |
| \u2028 | Line Separator | 行分隔符 |
| \u2029 | Paragraph Separator | 段落分隔符 |
案例
- #输出:['Dog', 'Cat', 'Elephant', 'Lion']
- animal = "Dog\nCat\nElephant\nLion"
- animalList = animal.splitlines()
- print(animalList)
-
- #输出:['Apple\n', 'Banana\r\n', 'Orange\u2028', 'Strawberry']
- fruit = "Apple\nBanana\r\nOrange\u2028Strawberry"
- fruitList = fruit.splitlines(True)
- print( fruitList)