Python中用于操作字符串的函数有很多,以下是一些常用的函数及其用法:
1. len():返回字符串的长度
```
s = "hello, world!"
print(len(s)) # 13
```
2. str():将对象转换为字符串类型
```
n = 123
s = str(n)
print(s) # "123"
```
3. upper():将字符串中所有字母都转换为大写
```
s = "hello, world!"
print(s.upper()) # "HELLO, WORLD!"
```
4. lower():将字符串中所有字母都转换为小写
```
s = "HELLO, WORLD!"
print(s.lower()) # "hello, world!"
```
5. capitalize():将字符串的首字母大写
```
s = "hello, world!"
print(s.capitalize()) # "Hello, world!"
```
6. title():将字符串中每个单词的首字母都大写
```
s = "hello, world!"
print(s.title()) # "Hello, World!"
```
7. swapcase():将字符串中大写字母转换为小写字母,小写字母转换为大写字母
```
s = "Hello, World!"
print(s.swapcase()) # "hELLO, wORLD!"
```
8. strip():去掉字符串两端的空格
```
s = " hello, world! "
print(s.strip()) # "hello, world!"
```
9. lstrip():去掉字符串左端的空格
```
s = " hello, world! "
print(s.lstrip()) # "hello, world! "
```
10. rstrip():去掉字符串右端的空格
```
s = " hello, world! "
print(s.rstrip()) # " hello, world!"
```
11. replace():替换字符串中的指定字符
```
s = "hello, world!"
print(s.replace("o", "0")) # "hell0, w0rld!"
```
12. count():统计字符串中指定字符的出现次数
```
s = "hello, world!"
print(s.count("l")) # 3
```
13. find():查找字符串中指定字符的位置
```
s = "hello, world!"
print(s.find("o")) # 4
```
14. index():查找字符串中指定字符的位置
```
s = "hello, world!"
print(s.index("o")) # 4
```
15. split():将字符串分割为多个子字符串
```
s = "hello, world!"
print(s.split(",")) # ["hello", " world!"]
```
16. join():将多个子字符串合并为一个字符串
```
l = ["hello", "world"]
s = " "
print(s.join(l)) # "hello world"
```
17. startswith():判断字符串是否以指定字符开头
```
s = "hello, world!"
print(s.startswith("h")) # True
```
18. endswith():判断字符串是否以指定字符结尾
```
s = "hello, world!"
print(s.endswith("!")) # True
```
19. isalpha():判断字符串是否只包含字母
```
s = "hello"
print(s.isalpha()) # True
```
20. isdigit():判断字符串是否只包含数字
```
s = "123"
print(s.isdigit()) # True
```
21. isalnum():判断字符串是否只包含数字和字母
```
s = "hello123"
print(s.isalnum()) # True
```
22. isspace():判断字符串是否只包含空格
```
s = " "
print(s.isspace()) # True
```
23. isupper():判断字符串中所有字母是否都是大写
```
s = "HELLO, WORLD!"
print(s.isupper()) # True
```
24. islower():判断字符串中所有字母是否都是小写
```
s = "hello, world!"
print(s.islower()) # True
```
25. istitle():判断字符串是否符合标题格式
```
s = "Hello, World!"
print(s.istitle()) # True
```
26. format():格式化字符串输出
```
name = "Tom"
age = 18
print("My name is {}, and I'm {} years old.".format(name, age))
# "My name is Tom, and I'm 18 years old."