字符串常用方法

1.capitalize() 方法:将字符串的首字母大写。

str = "hello, world"
print(str.capitalize())

输出:Hello, world

2.casefold() 方法:将字符串转换为小写并删除所有大小写特有的字符,使字符串可以比较。

str = "Hello, WORLD"
print(str.casefold())

输出:hello, world

使用场景:casefold()方法主要用于字符串比较。由于不同的语言可能会存在一些特殊字符或字母,这些字符或字母可能会因为大小写或形式上的细微差别导致比较结果不一致,进而影响程序的正确性。所以建议在需要进行字符串比较的时候,先使用casefold()方法将字符串标准化后再进行比较。

3.center() 方法:将字符串居中对齐,并使用指定字符填充不足的空间。

语法:

str.center(width[, fillchar])

其中,width代表最终字符串的总宽度,fillchar代表可选的填充字符,默认为空格。

代码示例:

语法:str.center(width[, fillchar])

str = "hello"
print(str.center(10, '-'))

输出:--hello---

4.count() 方法:返回字符串中指定子字符串的出现次数。

语法:

str.count(sub[, start[, end]])

其中,sub代表需要在字符串中查找的子字符串;start和end参数可选,用于指定查找的起始和结束位置,默认从字符串的开头到结尾进行查找。

代码示例:

str = "hello, world"
print(str.count('l'))

输出:3

5.encode() 方法:用于将字符串编码为指定的编码格式。

语法:

str.encode(encoding="utf-8",errors="strict")

其中,encoding参数代表所需的编码格式,默认为UTF-8编码;errors参数代表非法字符的处理方式,默认为“strict”,即遇到非法字符抛出异常。

errors参数可选的值包括:

  • “strict”:遇到非法字符时抛出异常;

  • “ignore”:忽略非法字符,直接删除;

  • “replace”:用?号代替非法字符;

  • “backslashreplace”:将非法字符转义为unicode编码

  • “xmlcharrefreplace”:将非法字符转义为XML实体编码。

代码示例:

str = "hello, world"
print(str.encode('utf-8'))

输出:b'hello, world'

6.endswith() 方法:判断字符串是否以指定子字符串结尾。

语法:

str.endswith(suffix[, start[, end]])

其中,suffix参数代表需要判断的子字符串;start和end参数可选,用于指定判断的起始和结束位置,默认从字符串的开头到结尾进行判断。

代码示例:

str = "hello, world"
print(str.endswith('ld'))

输出:True

7.expandtabs() 方法:将字符串中的制表符转换为指定数量的空格。

语法:

str.expandtabs(tabsize=8)

其中,tabsize参数代表tab字符的宽度,默认为8个空格。

代码示例:

str = "hello,\tworld"
print(str.expandtabs(4))

输出:hello, world

8.find() 方法:用于在字符串中查找指定的子串,返回子串出现的第一个位置,如果没有找到则返回-1。

语法:

str.find(sub[, start[, end]])

其中,sub参数代表需要查找的子字符串;start和end参数可选,用于指定查找的起始和结束位置,默认从字符串的开头到结尾进行查找。

代码示例:

str = "hello, world"
print(str.find('l'))

输出:2

9.format() 方法:将参数格式化为指定格式的字符串。

Python中字符串方法format()用于将指定的数据插入到字符串中的占位符中,生成新的字符串。该方法可以用于动态生成文本、日志记录、输出格式化等场景

语法:

str.format(*args, **kwargs)

可以通过位置参数或者关键字参数的方式为占位符提供数据,关键字参数的方式可以更容易地指定特定的数据类型和输出格式。

代码示例:

# 位置参数
s1 = "I have {} apples and {} oranges."
print(s1.format(3, 4))  # "I have 3 apples and 4 oranges."

# 命名参数
s2 = "The temperature is {temp:.1f}°C and the humidity is {hum:d}%."
print(s2.format(temp=25.6, hum=60))  # "The temperature is 25.6°C and the humidity is 60%."

# 访问字典和列表元素
name = ["Alice", "Bob"]
info = {"age": 25, "city": "Beijing"}
s3 = "My name is {0[0]} and I live in {1[city]}. I'm {1[age]} years old."
print(s3.format(name, info))  # "My name is Alice and I live in Beijing. I'm 25 years old."

输出:
I have 3 apples and 4 oranges.
The temperature is 25.6°C and the humidity is 60%.
My name is Alice and I live in Beijing. I'm 25 years old.

10.format_map() 方法:用于使用字典中的键值对替换字符串中的占位符,如果占位符没有对应的键,则抛出KeyError异常。

语法:

str.format_map(mapping)

其中,mapping参数是一个字典,字典中的键对应占位符中的变量名,字典中的值则替换为占位符的值。

代码示例

person = {'name': 'Alice', 'age': 25}
print("My name is {name} and I am {age} years old".format_map(person))

输出:My name is Alice and I am 25 years old

11.index() 方法:用于查找子字符串在原字符串中的索引位置,如果子字符串不存在,则抛出ValueError异常

语法:

str.index(sub[, start[, end]])

其中,sub参数代表需要查找的子字符串;start和end参数可选,用于指定查找的起始和结束位置,默认从字符串的开头到结尾进行查找。如果查找到了匹配的子字符串,则返回它在原字符串中第一个字符的索引。

代码示例:

s = "hello world"
print(s.index("world"))     # 6
print(s.index("Python"))    # ValueError: substring not found
print(s.index("l", 3))      # 3

12.isalnum() 方法:用于判断字符串中是否只包含字母和数字,如果是则返回True,否则返回False。

代码示例:

s1 = "hello123"
s2 = "hello world"
s3 = "hello123!"
print(s1.isalnum())  # True
print(s2.isalnum())  # False
print(s3.isalnum())  # False

13.isalpha() 方法:用于判断字符串中是否只包含字母,如果是则返回True,否则返回False。

代码示例:

s1 = "hello"
s2 = "Hello World"
s3 = "hello123"
print(s1.isalpha())  # True
print(s2.isalpha())  # False
print(s3.isalpha())  # False

14.isascii() 方法:用于判断字符串中的所有字符是否都是ASCII字符,如果是,则返回True,否则返回False。

代码示例:

s1 = "hello world"
s2 = "你好世界"
print(s1.isascii())  # True
print(s2.isascii())  # False

15.isdecimal() 方法:用于判断字符串中的所有字符是否都是十进制数字,如果是,则返回True,否则返回False。

代码示例:

s1 = "1234"
s2 = "12.34"
s3 = "一二三四"
print(s1.isdecimal())  # True
print(s2.isdecimal())  # False
print(s3.isdecimal())  # False

16.isdigit() 方法:用于判断字符串中的所有字符是否都是数字字符(0-9),如果是,则返回True,否则返回False。

s1 = "1234"
s2 = "12.34"
s3 = "一二三四"
print(s1.isdigit())  # True
print(s2.isdigit())  # False
print(s3.isdigit())  # False

17.isidentifier() 方法:检查字符串是否是一个有效的标识符(变量名)。

# 示例1
str1 = 'hello_world'
print(str1.isidentifier()) # True

# 示例2
str2 = 'This is a string'
print(str2.isidentifier()) # False

# 示例3
str3 = '1variable'
print(str3.isidentifier()) # False

# 示例4
str4 = 'if'
print(str4.isidentifier()) # False

18.islower() 方法:用于判断字符串是否全部由小写字母组成。

# 示例1
str1 = 'hello world'
print(str1.islower()) # True

# 示例2
str2 = 'Hello World'
print(str2.islower()) # False

# 示例3
str3 = 'HELLO WORLD'
print(str3.islower()) # False

# 示例4
str4 = '1234'
print(str4.islower()) # False

输出:True

19.isnumeric() 方法:用于判断一个字符串是否只包含数字字符。如果一个字符串只包含数字字符,则该方法返回True,否则返回False。

# 示例1
str1 = '12345'
print(str1.isnumeric()) # True

# 示例2
str2 = '1.23'
print(str2.isnumeric()) # False

# 示例3
str3 = '-123'
print(str3.isnumeric()) # False

# 示例4
str4 = '四'
print(str4.isnumeric()) # True

解释:

  • 对于示例1,'12345'是只包含数字字符,该方法返回True。
  • 对于示例2,'1.23'包含小数点,不是只包含数字字符,该方法返回False。
  • 对于示例3,'-123'包含负号,不是只包含数字字符,该方法返回False。
  • 对于示例4,'四'是一个汉字数字,ASCII码中没有对应的数字字符,但是在Unicode编码中表示为数字字符,因此该方法返回True。

20.isprintable() 方法:用于判断一个字符串中的所有字符是否都是可打印字符,如果一个字符串中的所有字符都是可打印字符,则该方法返回True,否则返回False。

# 示例1
str1 = 'hello world'
print(str1.isprintable()) # True

# 示例2
str2 = 'hello 
world'
print(str2.isprintable()) # False

# 示例3
str3 = 'hello\tworld'
print(str3.isprintable()) # True

# 示例4
str4 = '\x00'
print(str4.isprintable()) # False

函数名: isprintable()

函数功能:
isprintable()是Python的内置函数之一,用于判断一个字符串中的所有字符是否都是可打印字符。如果一个字符串中的所有字符都是可打印字符,则该方法返回True,否则返回False。可打印字符一般指ASCII码表中的除了控制字符外的所有字符。

参数说明:
isprintable()方法没有参数,只需要传递待检测的字符串即可。

代码示例:

# 示例1
str1 = 'hello world'
print(str1.isprintable()) # True

# 示例2
str2 = 'hello \nworld'
print(str2.isprintable()) # False

# 示例3
str3 = 'hello\tworld'
print(str3.isprintable()) # True

# 示例4
str4 = '\x00'
print(str4.isprintable()) # False

解释:

  • 对于示例1,'hello world'中的所有字符都是可打印字符,该方法返回True。

  • 对于示例2,'hello \nworld'中含有换行符,不是全部可打印字符,该方法返回False。

  • 对于示例3,'hello\tworld'中的制表符可被打印,该方法返回True。

  • 对于示例4,'\x00'是ASCII码表中的控制字符,不是可打印字符,该方法返回False。

21.isspace() 方法:用于判断一个字符串是否只由空白字符(包括空格、制表符、换行符等)组成。

方法功能:

用于判断一个字符串是否只由空白字符(包括空格、制表符、换行符等)组成。如果一个字符串只由空白字符组成,则该方法返回True,否则返回False

代码示例:

# 示例1
str1 = '     '
print(str1.isspace()) # True

# 示例2
str2 = 'hello world'
print(str2.isspace()) # False

# 示例3
str3 = '
\t '
print(str3.isspace()) # True

# 示例4
str4 = ''
print(str4.isspace()) # False

解释:

  • 对于示例1,' '只由空格字符组成,该方法返回True。
  • 对于示例2,'hello world'不只由空白字符组成,该方法返回False。
  • 对于示例3,'\t '包含空格、制表符、换行符,只有空格、制表符、换行符是空白字符,该方法返回True。
  • 对于示例4,''不包含任何字符,该方法返回False。

22.istitle() 方法:检查字符串中的单词是否都以大写字母开头并且其余字母都是小写字母。

方法功能:

用于判断一个字符串是否符合标题化规范。如果一个字符串符合标题化规范(即所有单词首字母大写,其余字母小写),则该方法返回True,否则返回False

# 示例1
str1 = 'Hello World'
print(str1.istitle()) # True

# 示例2
str2 = 'Hello world'
print(str2.istitle()) # False

# 示例3
str3 = 'HelloWorld'
print(str3.istitle()) # True

# 示例4
str4 = 'hello World'
print(str4.istitle()) # False

23.isupper() 方法:用于判断一个字符串是否全部由大写字母组成。

方法功能:

用于判断一个字符串是否全部由大写字母组成。如果一个字符串全部由大写字母组成,则该方法返回True,否则返回False。

代码示例:

# 示例1
str1 = 'HELLO WORLD'
print(str1.isupper()) # True

# 示例2
str2 = 'Hello World'
print(str2.isupper()) # False

# 示例3
str3 = 'hello world'
print(str3.isupper()) # False

# 示例4
str4 = '1234'
print(str4.isupper()) # False

解释:

  • 对于示例1,'HELLO WORLD'全部由大写字母组成,该方法返回True。
  • 对于示例2,'Hello World'含有小写字母,不是全部由大写字母组成,该方法返回False。
  • 对于示例3,'hello world'不包含大写字母,不是全部由大写字母组成,该方法返回False。
  • 对于示例4,'1234'不包含字母,不是全部由大写字母组成,该方法返回False。

24.join() 方法:将序列中的元素连接为一个字符串。

方法功能:

用于将一个字符串序列中的所有元素连接成一个字符串。连接时需要先将序列中的元素转换成字符串,然后在它们之间插入指定的分隔符。

代码示例:

# 示例1
lst1 = ['a', 'b', 'c']
sep1 = ', '
str1 = sep1.join(lst1)
print(str1) # a, b, c

# 示例2
lst2 = ['1', '2', '3', '4']
sep2 = '*'
str2 = sep2.join(lst2)
print(str2) # 1*2*3*4

# 示例3
lst3 = ['hello', 'world']
str3 = ''.join(lst3)
print(str3) # helloworld

# 示例4
lst4 = ['1', '2', '3', '4']
sep4 = ''
str4 = sep4.join(lst4)
print(str4) # 1234

# 示例5
lst5 = ['hello', 'world']
sep5 = ' '
str5 = sep5.join(lst5)
print(str5) # hello world

25.ljust() 方法:将字符串左对齐,并使用指定字符进行填充以满足指定长度。

方法语法:

str.ljust(width[, fillchar])

参数介绍:

  • width: 必需,指定字符串输出的宽度。

  • fillchar: 可选,填充字符,缺省为英文的空格。

代码示例:

# 示例1:指定宽度为10,使用*号填充
str1 = "Hello"
print(str1.ljust(10, "*"))
# 输出:Hello*****

# 示例2:指定宽度为10,使用空格填充
str2 = "World"
print(str2.ljust(10))
# 输出:World     

# 示例3:指定宽度为5,使用$号进行填充
str3 = "Python"
print(str3.ljust(5, '$'))
# 输出:Python

# 示例4:指定宽度为6,使用$号进行填充
str4 = "Python"
print(str4.ljust(6, '$'))
# 输出:Python

# 示例5:指定宽度为0,不进行填充
str5 = "Python"
print(str5.ljust(0, '$'))
# 输出:Python

26.rjust() 方法:将字符串右对齐,并使用指定字符进行填充以满足指定长度。

方法功能:

rjust()方法用于对字符串进行右对齐,并使用指定的字符在左边进行填充以满足指定长度。

语法:

str.rjust(width[, fillchar])

参数说明:

  • width: 必需,指定字符串输出的宽度。
  • fillchar: 可选,填充字符,默认为空格。

代码示例:

# 示例1:指定宽度为10,使用+号填充
str1 = "Hello"
print(str1.rjust(10, "+"))
# 输出:+++++Hello

# 示例2:指定宽度为10,使用空格填充
str2 = "World"
print(str2.rjust(10))
# 输出:     World

# 示例3:指定宽度为5,使用$号进行填充
str3 = "Python"
print(str3.rjust(5, '$'))
# 输出:Python

# 示例4:指定宽度为6,使用$号进行填充
str4 = "Python"
print(str4.rjust(6, '$'))
# 输出:Python

# 示例5:指定宽度为0,不进行填充
str5 = "Python"
print(str5.rjust(0, '$'))
# 输出:Python

27.lower() 方法:将字符串中的所有英文字符转换为小写字母,并返回转换后的结果。

str1 = "Hello World!"
str2 = "Python"
str3 = "UPPER CASE"

print(str1.lower())   # 输出:hello world!
print(str2.lower())   # 输出:python
print(str3.lower())   # 输出:upper case

28.strip()方法:用于删除字符串两端的空格或指定字符,并返回删除后的结果

语法:

str.strip([chars])

参数说明:

chars:可选参数,指定删除的字符,如果为空,则删除两端的空格。

代码示例:

str1 = "   Hello World!   "
str2 = "=====Python====="
 
print(str1.strip())            # 输出:Hello World!  
print(str2.strip('='))         # 输出:Python

解释:

  • 对于第一个示例,字符串" Hello World! "两端的空格被删除掉了,返回"Hello World!"。
  • 对于第二个示例,字符串"=Python="两端的=号被删除掉了,返回"Python"。

29.lstrip() 方法:用于删除字符串左边的空格或指定字符,并返回删除后的结果。

函数功能:

lstrip() 方法用于删除字符串左边的空格或指定字符,并返回删除后的结果。

语法:

str.lstrip([chars])

参数说明:

chars:可选参数,指定删除的字符,如果为空,则删除左边的空格。

代码示例:

str1 = "   Hello World!   "
str2 = "=====Python====="

print(str1.lstrip())            # 输出:Hello World!   
print(str2.lstrip('='))         # 输出:Python=====

解释:

  • 对于第一个示例,字符串" Hello World! "左边的空格被删除掉了,返回"Hello World! "。
  • 对于第二个示例,字符串"=Python="左边的=号被删除掉了,返回"Python====="。

30.rstrip() 方法:用于删除字符串右边的空格或指定字符,并返回删除后的结果。

语法:

str.rstrip([chars])

参数说明:

chars(可选):表示从右侧中需要删除的字符集

代码示例:

string1 = "  abc  "
print(string1.rstrip())       # 输出 "   abc"

string2 = "  abc!  "
print(string2.rstrip(" !"))   # 输出 "  abc"

string3 = """abc  

"""
print(string3.rstrip())       # 输出 "abc"

31.maketrans方法:适用于在处理数据时替换多个字符或字符集合

函数功能:

用于创建一个对应映射表,该映射表可用于 str.translate() 方法。它适用于在处理数据时替换多个字符或字符集合。

语法:

str.maketrans(x[, y[, z]])

参数介绍:

  • x:必需,如果只有一个参数,需要使用一个表示每个字符的字符串。
  • y:可选,代表着另一个字符串;给定两个参数时,具有相同长度和相同索引的字符串将被映射为每个字符。
  • z:可选,代表着一个字符串,其中所有字符都被视为待删除的字符。

需要注意的是,当使用一个参数时,需要将该参数视为一个长度为256的表,其中表中每个索引都代表将被转换的Unicode字符值。

代码示例:

创建基于映射表的转换器:

intab = "aeiou"
outtab = "12345"
mapping = str.maketrans(intab, outtab)
string = "this is a string"
print(string.translate(mapping))  # 输出 "th3s 3s 1 str3ng"

指定一个用于删除字符的表:

delchars = "aeiou"
mapping = str.maketrans("", "", delchars)
string = "this is a string"
print(string.translate(mapping))  # 输出 "ths s  strng"

32.translate方法:用于对字符串执行高级替换或删除操作

函数功能:

translate() 方法返回一个执行 Unicode 字符串转换的新字符串。它可以用于对字符串执行高级替换或删除操作。

语法:

str.translate(table[, deletechars])

参数介绍:

  • table:必需,翻译表,可以通过 str.maketrans() 方法创建,或者是一个长度为 256 的字符逐一映射的字符串
  • deletechars:可选,表示需要删除的字符集合。

代码示例:

创建基于映射表的转换器:

intab = "aeiou"
outtab = "12345"
mapping = str.maketrans(intab, outtab)
string = "this is a string"
print(string.translate(mapping))  # 输出 "th3s 3s 1 str3ng"

指定一个用于删除字符的表:

delchars = "aeiou"
mapping = str.maketrans("", "", delchars)
string = "this is a string"
print(string.translate(mapping))  # 输出 "ths s  strng"

33.partition() 方法:查找子字符串,并将其拆分为三部分:前缀、子字符串、后缀。

函数功能:

用于在字符串中查找指定的子字符串,将字符串分成三个部分:待查找字符串之前的部分、待查找的字符串、待查找字符串之后的部分,并以元组形式返回。

语法:

str.partition(sep)

参数sep:待查找的子字符串。

代码示例:

s1 = "hello, world!"
print(s1.partition(","))
# ('hello', ',', ' world!')

s2 = "www.baidu.com"
print(s2.partition("."))
# ('www', '.', 'baidu.com')

s3 = "hello123world"
print(s3.partition("123"))
# ('hello', '123', 'world')

34.replace() 方法:将字符串中的子字符串替换为另一个字符串。

函数功能:

replace方法用于将字符串中的指定子字符串替换成另一个字符串,并返回替换后的新字符串。

语法:

str.replace(old, new[, count])

参数说明:

  • 参数old:需要被替换的子字符串。
  • 参数new:用于替换的新字符串。
  • 可选参数count:指定替换的次数,如果不指定,则替换所有。

代码示例:

s = "hello, world!"
s = s.replace("l", "L")
print(s)
# 'heLLo, worLd!'

35.rfind() 方法:从右侧开始查找字符串中指定子字符串的位置。

函数功能:

rfind方法用于在字符串中从右向左查找指定的子字符串,并返回第一次出现的位置。如果没找到,则返回-1。

语法:

str.rfind(sub[, start[, end]])

参数说明:

  • sub为必要参数,表示需要查找的子字符串。
  • start为可选参数,表示开始查找的位置,默认为0。
  • end为可选参数,表示结束查找的位置,默认为字符串的长度。

代码示例:

s = "hello, world!"
pos = s.rfind(",")
print(pos)
# 5

36.rindex() 方法:从右侧开始查找字符串中指定子字符串的位置。与 rfind() 方法相似,但子字符串不存在时会抛出异常。

语法:

str.rindex(sub[, start[, end]])

参数说明:

  • 参数sub:待查找的子字符串。
  • 可选参数start:开始查找的位置,默认为0。
  • 可选参数end:结束查找的位置,默认为字符串的长度。

代码示例:

s = "hello, world!"
pos = s.rindex(",")
print(pos)
# 5

37.rpartition() 方法:从右边开始查找子字符串,并将其拆分为三部分:前缀、子字符串、后缀。

语法:

str.rpartition(sep)

参数sep:待查找的子字符串。

代码示例:

s = "www.baidu.com"
print(s.rpartition("."))
# ('www.baidu', '.', 'com')

38.split() 方法:将字符串从左边开始拆分为指定数量的子字符串,并将这些子字符串作为列表返回。默认情况下,字符串根据空格进行拆分,但是可以指定分隔符。

函数功能:

split方法用于将字符串从左向右通过分隔符进行切分,返回一个列表。

语法:

str.split([sep[,maxsplit]])

参数说明:

  • 参数sep:用于分割字符串的分隔符,默认为所有的空字符,包括空格、换行符、制表符等。
  • 参数maxsplit:分割的最大次数,默认为-1,表示所有。

代码示例:

s = 'hello world  nice 
to see you'
lst = s.split(' ',2)
print(lst)
# ['hello', 'world', ' nice 
to see you']

39.rsplit() 方法:将字符串从右侧开始拆分为指定数量的子字符串,并返回这些子字符串作为列表。

函数功能:

rsplit方法用于将字符串通过分隔符进行切分,返回一个列表。与split方法不同的是,rsplit方法从右边开始切分。

语法:

str.rsplit([sep[, maxsplit]])
  • 参数sep:用于分割字符串的分隔符,默认为所有的空字符,包括空格、换行符、制表符等。
  • 参数maxsplit:分割的最大次数,默认为-1,表示所有。

代码示例:

s = 'hello, world!'
lst = s.rsplit(',')
print(lst)
# ['hello', ' world!']

40.splitlines() 方法:将字符串拆分为行,并将这些行作为列表返回。

函数功能:

splitlines方法用于将字符串按照行分隔符进行切分,返回一个包含各行的列表。

语法:

str.splitlines([keepends])

参数keepends:默认为False,如果为True,则保留换行符,如果为False,则不包含换行符。

代码示例:

s = 'hello
world
'
#使用换行符进行切分,将字符串s分成两行,分别存储在列表lst中。
lst = s.splitlines()
print(lst)
# ['hello', 'world']


s1 = 'hello
world
'
使用换行符进行切分,将字符串s分成两行,并保留每行的换行符,分别存储在列表lst中。
lst1 = s1.splitlines(keepends=True)
print(lst1)
['hello
', 'world
']

41.startswith() 方法:检查字符串是否以指定子字符串开头。

函数功能:

startswith方法用于检查字符串是否以指定的前缀开始,返回一个布尔值。

语法:

str.startswith(prefix[, start[, end]])

参数说明:

  • 参数prefix:必选参数,指定的前缀。
  • 参数start:可选参数,表示检索的起始位置,默认为0。
  • 参数end:可选参数,表示检索的结束位置,默认为字符串的长度。
string = 'Hello, world!'
result = string.startswith('Hello')
print(result)
True

在检查字符串是否以'world'开头之前,将字符串的起始位置设置为7,也就是从', '和'w'之间的空格开始检查,返回True。
string1 = 'Hello, world!'
result = string1.startswith('world', 7)
print(result)
True

42.swapcase() 方法:交换字符串中大写字母和小写字母的位置。

函数功能:

swapcase方法用于将所有大写字母转换为小写字母,将所有小写字母转换为大写字母,并返回转换后的字符串。

语法:

str.swapcase()

代码示例:

str = 'Hello, WORLD!'
result = str.swapcase()
print(result)
hELLO, world!

43.title() 方法:将字符串中的每个单词的第一个字母变为大写。

函数功能:

title方法用于将字符串的每个单词的首字母大写,返回修改后的字符串。

语法:

str.title()

代码示例:

str = 'hello world'
result = str.title()
print(result)
# Hello World

44.upper() 方法:将字符串转换为大写。

函数功能:

upper方法用于将字符串中的小写字母转换成大写字母,并返回修改后的字符串。

语法:

str.upper()

代码示例:

str = 'hello world'
result = str.upper()
print(result)
# HELLO WORLD

45.zfill() 方法:将字符串填充到指定长度,并在左侧使用零字符('0')进行填充。

函数功能:

zfill方法用于将字符串变量变为指定长度的字符串,并在左侧填充0。

语法:

str.zfill(width)

参数说明:

width为填充后的字符串长度。如果原字符串长度大于width,则返回原字符串。

代码示例:

str1 = '123'
result = str1.zfill(5)
print(result)
# 00123

str2 = '-123'
result = str2.zfill(5)
print(result)
# -0123
posted @ 2023-03-30 20:45  我不知道取什么名字好  阅读(76)  评论(0编辑  收藏  举报