字符串处理的20个Python函数及用法示例
1. len(string)
用于返回字符串的长度。
例如:
string = "Hello World"
print(len(string)) # 输出为 11
2. string.replace(old, new)
用于将字符串中的旧字符替换为新字符。
例如:
string = "Hello World"
new_string = string.replace("o", "0")
print(new_string) # 输出为 Hell0 W0rld
3. string.lower()
用于将字符串中的所有字符转换为小写。
例如:
string = "Hello World"
new_string = string.lower()
print(new_string) # 输出为 hello world
4. string.upper()
用于将字符串中的所有字符转换为大写。
例如:
string = "Hello World"
new_string = string.upper()
print(new_string) # 输出为 HELLO WORLD
5. string.strip()
用于删除字符串中的空格。
例如:
string = " Hello World "
new_string = string.strip()
print(new_string) # 输出为 Hello World
6. string.split(separator)
用于将字符串分割成列表。
例如:
string = "Hello,World"
new_list = string.split(",")
print(new_list) # 输出为 ['Hello', 'World']
7. string.join(iterable)
用于将可迭代对象中的元素以字符串形式连接在一起。
例如:
list = ["Hello", "World"]
new_string = "-".join(list)
print(new_string) # 输出为 Hello-World
8. string.startswith(substring)
用于检查字符串是否以指定子字符串开头。
例如:
string = "Hello World"
result = string.startswith("Hello")
print(result) # 输出为 True
9. string.endswith(substring)
用于检查字符串是否以指定子字符串结尾。
例如:
string = "Hello World"
result = string.endswith("World")
print(result) # 输出为 True
10. string.find(substring)
用于查找字符串中指定子字符串的位置。
例如:
string = "Hello World"
position = string.find("World")
print(position) # 输出为 6
11. string.count(substring)
用于计算字符串中指定子字符串出现的次数。
例如:
string = "Hello World"
count = string.count("o")
print(count) # 输出为 2
12. string.isalnum()
用于检查字符串是否只包含字母和数字。
例如:
string = "Hello World"
result = string.isalnum()
print(result) # 输出为 False
13. string.isalpha()
用于检查字符串是否只包含字母。
例如:
string = "Hello World"
result = string.isalpha()
print(result) # 输出为 False
14. string.isnumeric()
用于检查字符串是否只包含数字。
例如:
string = "12345"
result = string.isnumeric()
print(result) # 输出为 True
15. string.islower()
用于检查字符串中的所有字母是否都为小写。
例如:
string = "hello world"
result = string.islower()
print(result) # 输出为 True
16. string.isupper()
用于检查字符串中的所有字母是否都为大写。
例如:
string = "HELLO WORLD"
result = string.isupper()
print(result) # 输出为 True
17. string.capitalize()
用于将字符串的 个字母转换为大写。
例如:
string = "hello world"
new_string = string.capitalize()
print(new_string) # 输出为 Hello world
18. string.title()
用于将字符串中每个单词的 个字母转换为大写。
例如:
string = "hello world"
new_string = string.title()
print(new_string) # 输出为 Hello World
19. string.swapcase()
用于将字符串中的所有小写字母转换为大写字母,所有大写字母转换为小写字母。
例如:
string = "Hello World"
new_string = string.swapcase()
print(new_string) # 输出为 hELLO wORLD
20. string.zfill(width)
用于在字符串左侧填充0,直到字符串长度达到指定宽度。
例如:
string = "123"
new_string = string.zfill(5)
print(new_string) # 输出为 00123
