Python中字符串的内置方法允许你执行各种操作,例如转换大小写、查找子串、替换字符等。以下是一些常用的内置方法:
1. `capitalize()`: 将字符串的第一个字符转换为大写,其余字符转换为小写。
s = "hello world"
print(s.capitalize()) 输出 "Hello world"
2. `lower()`: 将字符串中的所有大写字母转换为小写字母。
s = "HELLO WORLD"
print(s.lower()) 输出 "hello world"
3. `upper()`: 将字符串中的所有小写字母转换为大写字母。
s = "hello world"
print(s.upper()) 输出 "HELLO WORLD"
4. `count(sub[, start[, end]])`: 返回子串 `sub` 在字符串中出现的次数,`start` 和 `end` 参数表示范围。
s = "hello world, world!"
print(s.count("world")) 输出 2
5. `encode(encoding='utf-8', errors='strict')`: 以指定的编码格式对字符串进行编码,默认编码为 'utf-8',错误处理为 'strict'。
s = "你好,世界!"
encoded_s = s.encode('utf-8')
print(encoded_s) 输出 b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
6. `endswith(sub[, start[, end]])`: 检查字符串是否以子串 `sub` 结尾,`start` 和 `end` 参数表示范围。
s = "hello world!"
print(s.endswith("world!")) 输出 True
7. `expandtabs([tabsize=8])`: 把字符串中的制表符 `\t` 转换为指定数量的空格,默认 `tabsize` 为 8。
s = "hello\tworld"
print(s.expandtabs()) 输出 "helloworld"
8. `find(sub[, start[, end]])`: 查找子串 `sub` 在字符串中首次出现的位置,如果未找到则返回 -1,`start` 和 `end` 参数表示范围。
s = "hello world"
print(s.find("world")) 输出 6
9. `index(sub[, start[, end]])`: 类似于 `find`,但如果 `sub` 不在字符串中会产生一个异常。
s = "hello world"
print(s.index("planet")) 抛出 ValueError 异常
10. `isalnum()`: 如果字符串至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False。
s = "hello123"
print(s.isalnum()) 输出 True
11. `isalpha()`: 如果字符串中的所有字符都是字母则返回 True,否则返回 False。
s = "hello123"
print(s.isalpha()) 输出 False
这些方法只是Python字符串众多内置方法中的一部分。你可以根据需要选择合适的方法来操作字符串