当涉及到Python中字符串的方法和函数时,有许多内置工具可供使用。以下是一些常用的字符串方法和函数,以及它们的用法和示例:
常用字符串方法
-
str.capitalize()
:- 将字符串的第一个字符转换为大写,其余字符转换为小写。
s = "hello, world" print(s.capitalize()) # 输出: "Hello, world"
-
str.upper()
:- 将字符串中的所有字符转换为大写。
s = "hello, world" print(s.upper()) # 输出: "HELLO, WORLD"
-
str.lower()
:- 将字符串中的所有字符转换为小写。
s = "HELLO, WORLD" print(s.lower()) # 输出: "hello, world"
-
str.isupper()
:- 检查字符串中的所有字符是否都是大写。
s = "HELLO, WORLD" print(s.isupper()) # 输出: True
-
str.islower()
:- 检查字符串中的所有字符是否都是小写。
s = "hello, world" print(s.islower()) # 输出: True
-
str.isdigit()
:- 检查字符串中的所有字符是否都是数字字符。
s = "123" print(s.isdigit()) # 输出: True
-
str.split(sep=None)
:- 将字符串分割成子字符串列表。可以通过
sep
参数指定分隔符,默认情况下使用空格作为分隔符。
s = "hello, world" print(s.split()) # 输出: ['hello,', 'world']
- 将字符串分割成子字符串列表。可以通过
-
str.strip(chars=None)
:- 返回一个去除了开头和结尾指定字符
chars
的字符串副本。如果未指定chars
,则默认删除空白字符。
s = " hello, world " print(s.strip()) # 输出: "hello, world"
- 返回一个去除了开头和结尾指定字符
-
str.replace(old, new)
:- 将字符串中的所有子字符串
old
替换为new
。
s = "hello, world" print(s.replace("hello", "hi")) # 输出: "hi, world"
- 将字符串中的所有子字符串
-
str.join(iterable)
:- 将可迭代对象
iterable
中的所有字符串连接成一个字符串,使用当前字符串作为分隔符。
s = "," print(s.join(["apple", "banana", "cherry"])) # 输出: "apple,banana,cherry"
- 将可迭代对象
-
str.startswith(prefix)
和str.endswith(suffix)
:- 检查字符串是否以指定的前缀或后缀开始或结束,返回
True
或False
。
s = "hello, world" print(s.startswith("hello")) # 输出: True print(s.endswith("world")) # 输出: True
- 检查字符串是否以指定的前缀或后缀开始或结束,返回
-
str.find(sub)
和str.index(sub)
:- 在字符串中搜索子字符串
sub
,并返回第一个匹配项的索引。如果没有找到,find()
返回-1,index()
引发ValueError
异常。
s = "hello, world" print(s.find("world")) # 输出: 7 print(s.index("world")) # 输出: 7
- 在字符串中搜索子字符串
-
str.count(sub)
:- 返回子字符串
sub
在字符串中出现的次数。
s = "hello, world" print(s.count("l")) # 输出: 3
- 返回子字符串
-
str.format()
:- 格式化字符串,用参数替换字符串中的占位符。
name = "Alice" age = 30 print("My name is {} and I am {} years old.".format(name, age))