在Python中,字符串是不可变的序列类型,包含许多内置的方法来操作和处理字符串。以下是一些常用的字符串方法:
1. str.upper()
和 str.lower()
将字符串转换为大写或小写。
s = "Hello, World!"
print(s.upper()) # 输出: HELLO, WORLD!
print(s.lower()) # 输出: hello, world!
2. str.strip()
, str.lstrip()
, str.rstrip()
移除字符串两端(或指定方向)的空白字符或指定字符。
s = " Hello, World! "
print(s.strip()) # 输出: "Hello, World!"
print(s.lstrip()) # 输出: "Hello, World! "
print(s.rstrip()) # 输出: " Hello, World!"
3. str.split()
和 str.join()
分割字符串为列表或将列表中的字符串合并为一个字符串。
s = "Hello, World!"
print(s.split()) # 输出: ['Hello,', 'World!']
print(s.split(',')) # 输出: ['Hello', ' World!']
words = ["Hello", "World"]
print(" ".join(words)) # 输出: "Hello World"
4. str.replace()
替换字符串中的指定子字符串。
s = "Hello, World!"
print(s.replace("World", "Python")) # 输出: "Hello, Python!"
5. str.find()
和 str.index()
查找子字符串在字符串中的位置。find
方法在找不到子字符串时返回 -1,index
方法则会引发 ValueError
异常。
s = "Hello, World!"
print(s.find("World")) # 输出: 7
print(s.index("World")) # 输出: 7
#print(s.find("Python")) # 输出: -1
#print(s.index("Python")) # ValueError: substring not found
6. str.startswith()
和 str.endswith()
检查字符串是否以指定的前缀或后缀开头或结尾。
s = "Hello, World!"
print(s.startswith("Hello")) # 输出: True
print(s.endswith("World!")) # 输出: True
7. str.capitalize()
, str.title()
, str.swapcase()
修改字符串的大小写。
s = "hello, world!"
print(s.capitalize()) # 输出: "Hello, world!"
print(s.title()) # 输出: "Hello, World!"
print(s.swapcase()) # 输出: "HELLO, WORLD!"
8. str.isalpha()
, str.isdigit()
, str.isalnum()
, str.isspace()
检查字符串是否全为字母、数字、字母和数字的组合或空白字符。
s1 = "Hello"
s2 = "1234"
s3 = "Hello123"
s4 = " "
print(s1.isalpha()) # 输出: True
print(s2.isdigit()) # 输出: True
print(s3.isalnum()) # 输出: True
print(s4.isspace()) # 输出: True
9. str.count()
计算子字符串在字符串中出现的次数。
s = "Hello, World! Hello!"
print(s.count("Hello")) # 输出: 2
10. str.format()
字符串格式化。
name = "Alice"
age = 30
s = "My name is {} and I am {} years old.".format(name, age)
print(s) # 输出: My name is Alice and I am 30 years old.
11. str.zfill()
在字符串前填充零,以达到指定的长度。
s = "42"
print(s.zfill(5)) # 输出: "00042"
12. str.partition()
和 str.rpartition()
将字符串分割成三部分:分隔符前的部分、分隔符本身、分隔符后的部分。
s = "Hello, World!"
print(s.partition(",")) # 输出: ('Hello', ',', ' World!')
print(s.rpartition(",")) # 输出: ('Hello', ',', ' World!')