创建字符串
s = "Hello, World!"
常用字符串操作
- 获取字符串长度
length = len(s)
print(length) # 输出: 13
- 字符串拼接
s1 = "Hello"
s2 = "World"
s3 = s1 + ", " + s2 + "!"
print(s3) # 输出: Hello, World!
- 重复字符串
s = "Hello"
s_repeated = s * 3
print(s_repeated) # 输出: HelloHelloHello
- 字符串格式化
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # 输出: My name is Alice and I am 30 years old.
- 字符串分割
s = "Hello, World!"
parts = s.split(", ")
print(parts) # 输出: ['Hello', 'World!']
- 字符串连接
words = ["Hello", "World"]
joined_string = " ".join(words)
print(joined_string) # 输出: Hello World
- 字符串替换
s = "Hello, World!"
new_s = s.replace("World", "Python")
print(new_s) # 输出: Hello, Python!
- 字符串查找
s = "Hello, World!"
index = s.find("World")
print(index) # 输出: 7
- 字符串大小写转换
s = "Hello, World!"
print(s.upper()) # 输出: HELLO, WORLD!
print(s.lower()) # 输出: hello, world!
print(s.capitalize()) # 输出: Hello, world!
print(s.title()) # 输出: Hello, World!
- 去除空白字符
s = " Hello, World! "
print(s.strip()) # 输出: Hello, World!
print(s.lstrip()) # 输出: Hello, World!
print(s.rstrip()) # 输出: Hello, World!
子字符串的用法
- 获取子字符串
s = "Hello, World!"
sub_s = s[7:12]
print(sub_s) # 输出: World
- 检查子字符串
s = "Hello, World!"
print("World" in s) # 输出: True
print("Python" in s) # 输出: False
- 子字符串计数
s = "Hello, World! Hello, Python!"
count = s.count("Hello")
print(count) # 输出: 2
- 子字符串索引
s = "Hello, World!"
index = s.index("World")
print(index) # 输出: 7
# 如果子字符串不存在,会抛出 ValueError
try:
index = s.index("Python")
except ValueError:
print("Substring not found")
- 子字符串切片
s = "Hello, World!"
sub_s = s[7:] # 从索引 7 开始到结尾
print(sub_s) # 输出: World!
sub_s = s[:5] # 从开头到索引 5(不包括 5)
print(sub_s) # 输出: Hello
sub_s = s[::2] # 每隔一个字符取一个
print(sub_s) # 输出: Hlo ol!
str.find()与str.index()
使用 str.find()
方法查找子字符串时,如果子字符串不存在于原字符串中,find()
方法不会报错,而是返回 -1
。 str.index()
在找不到子字符串时会抛出 ValueError
异常。
str.find()
s = "Hello, World!"
index = s.find("World")
print(index) # 输出: 7
# 查找不存在的子字符串
index = s.find("Python")
print(index) # 输出: -1
str.index()
s = "Hello, World!"
index = s.index("World")
print(index) # 输出: 7
# 查找不存在的子字符串,会抛出 ValueError
try:
index = s.index("Python")
except ValueError:
print("Substring not found") # 输出: Substring not found
str.find(substring)
:返回子字符串在原字符串中的最低索引,如果找不到则返回-1
。str.index(substring)
:返回子字符串在原字符串中的最低索引,如果找不到则抛出ValueError
。