Python的字符串(str)类型提供了许多内置的操作方法,允许你以各种方式处理和操作字符串。以下是一些常见的字符串操作方法:
访问字符串中的字符:
使用索引(str[index]
):返回指定索引处的字符。
切片(str[start:stop:step]
):返回一个新的字符串,它是此字符串的一个子字符串。
s = "Hello, world!"
print(s[0]) # 输出: H
print(s[7:12]) # 输出: world
修改字符串
注意:Python中的字符串是不可变的,但以下方法会返回新的字符串
upper()
:将字符串中的所有字符转换为大写。
s = "hello"
upper_s = s.upper() # 转换为大写
print(upper_s) # 输出: HELLO
lower()
:将字符串中的所有字符转换为小写。
s = "hello"
lower_s = s.lower() # 转换为小写
print(lower_s) # 输出: hello
capitalize()
:将字符串的第一个字符转换为大写,其余字符转换为小写。
# 定义一个字符串
s = "hello"
# 使用 capitalize() 方法将字符串的第一个字符转换为大写
capitalized_s = s.capitalize()
print(capitalized_s) # 输出: Hello
title()
:将字符串中的每个单词的首字母转换为大写。
# 定义一个字符串
s = "hello, world! this is a test string."
# 使用 title() 方法将每个单词的首字母转换为大写
titled_s = s.title()
print(titled_s)
# 输出: Hello, World! This Is A Test String.
swapcase()
:将字符串中的所有大写字母转换为小写,所有小写字母转换为大写。
# 定义一个字符串
s = "Hello, World! This Is A Test String."
# 使用 swapcase() 方法将字符串中的大小写字母互换
swapped_s = s.swapcase()
print(swapped_s)
# 输出: hELLO, wORLD! tHIS iS a tEST sTRING.
replace(old, new[, count])
:返回一个新的字符串,其中指定的旧子字符串被新子字符串替换。如果指定了count,则替换不会超过count次。
replace_s = s.replace("l", "w") # 替换字符
print(replace_s) # 输出: hewwo
strip([chars])、lstrip([chars])、rstrip([chars])
:分别删除字符串两端的(左端或右端)指定字符(默认为空白字符)。
stripped_s = s.strip() # 去除两端空白
print(stripped_s)