1. capitalize()
将字符串的首字母变为大写,其余字母变为小写。
text = "hello world"
print(text.capitalize()) # 输出: "Hello world"
2. upper()
将字符串中的所有字母都转换为大写。
text = "hello world"
print(text.upper()) # 输出: "HELLO WORLD"
3. lower()
将字符串中的所有字母都转换为小写。
text = "HELLO World"
print(text.lower()) # 输出: "hello world"
4. strip()
删除字符串开头和结尾的空白字符(包括空格、制表符、换行符等)。
text = " hello world \n"
print(text.strip()) # 输出: "hello world"
5. find(sub[, start[, end]])
搜索子字符串sub
,如果找到,则返回第一次出现的索引,否则返回-1。
text = "hello world"
print(text.find("world")) # 输出: 6
print(text.find("python")) # 输出: -1
6. replace(old, new[, count])
将字符串中的old
替换为new
,如果指定了count
,则只替换前count
次出现。
text = "hello world world"
print(text.replace("world", "python")) # 输出: "hello python python"
print(text.replace("world", "python", 1)) # 输出: "hello python world"
7. split(sep=None, maxsplit=-1)
根据分隔符sep
分割字符串,返回一个列表。如果sep
未指定,任何空白字符都被视为分隔符。
text = "hello world python"
print(text.split()) # 输出: ['hello', 'world', 'python']
print(text.split(" ", 1)) # 输出: ['hello', 'world python']
8. join(iterable)
将iterable
中的元素(必须是字符串)合并为一个新字符串,元素之间使用调用此方法的字符串作为分隔符。
words = ["hello", "world", "python"]
print(" ".join(words)) # 输出: "hello world python"
9. count(sub[, start[, end]])
返回子字符串sub
在指定范围内出现的次数。
text = "hello world world"
print(text.count("world")) # 输出: 2
10. startswith(prefix[, start[, end]])
检查字符串是否以prefix
开始。
text = "hello world"
print(text.startswith("hello")) # 输出: True
11. endswith(suffix[, start[, end]])
检查字符串是否以suffix
结束。
text = "hello world"
print(text.endswith("world")) # 输出: True
12. isnumeric()
检查字符串中的所有字符是否都是数字,并且字符串至少有一个字符。
text = "12345"
print(text.isnumeric()) # 输出: True
13. isalpha()
检查字符串中的所有字符是否都是字母,并且字符串至少有一个字符。
text = "hello"
print(text.isalpha()) # 输出: True
14. isalnum()
检查字符串中的所有字符是否都是字母或数字,并且字符串至少有一个字符。
text = "hello123"
print(text.isalnum()) # 输出: True
15. isspace()
检查字符串中的所有字符是否都是空白字符,并且字符串至少有一个字符。
text = " \t\n"
print(text.isspace()) # 输出: True
16. istitle()
检查字符串是否为标题化的(即所有单词的首字母大写,其余字母小写)。
text = "Hello World"
print(text.istitle()) #


本文含有隐藏内容,请 开通VIP 后查看