字符串
声明字符串
s0: str = '张三'
s1 = '张三'
s2 = "李四"
s3 = 'i\'m july'
s4 = "i'm bob"
s5 = "我是换行的\n字符串"
s6 = '我是"四川"人'
s7 = """我是换行的
字符串
"""
s8 = '''我也是换行的
字符串
'''
下标操作
# 第一个
print(s1[0]) # 输出 张
# 最后一个
print(s6(-1)) # 输出 人
# 长度
print(len(s1)) # 输出 2
# 切片(切片具体用法在通用操作中详细解释)
print(s4[0:5:1]) # 输出 i'm b
# 这样做会报错,因为字符串不可变(可以使用 replace 方法来替换,这样是返回一个新的字符串,原来的字符串不会变)
s[0] = "王"
常用函数
| 方法名 |
描述 |
示例 |
| 查找与判断 |
|
|
find(sub) |
返回子字符串 sub 第一次出现的索引,未找到返回 -1。 |
"hello".find("e") → 1 |
rfind(sub) |
返回子字符串 sub 最后一次出现的索引,未找到返回 -1。 |
"hello".rfind("l") → 3 |
index(sub) |
返回子字符串 sub 第一次出现的索引,未找到抛出 ValueError。 |
"hello".index("e") → 1 |
rindex(sub) |
返回子字符串 sub 最后一次出现的索引,未找到抛出 ValueError。 |
"hello".rindex("l") → 3 |
count(sub) |
返回子字符串 sub 出现的次数。 |
"hello".count("l") → 2 |
startswith(prefix) |
检查字符串是否以 prefix 开头,返回布尔值。 |
"hello".startswith("he") → True |
endswith(suffix) |
检查字符串是否以 suffix 结尾,返回布尔值。 |
"hello".endswith("lo") → True |
| 大小写转换 |
|
|
lower() |
将字符串转换为小写。 |
"Hello".lower() → "hello" |
upper() |
将字符串转换为大写。 |
"Hello".upper() → "HELLO" |
capitalize() |
将字符串首字母大写,其余字母小写。 |
"hello".capitalize() → "Hello" |
title() |
将每个单词的首字母大写。 |
"hello world".title() → "Hello World" |
swapcase() |
将字符串中的大小写互换。 |
"Hello".swapcase() → "hELLO" |
| 替换与填充 |
|
|
replace(old, new) |
将字符串中的 old 替换为 new。 |
"hello".replace("l", "L") → "heLLo" |
strip() |
去除字符串两端的空白字符(包括空格、换行符等)。 |
" hello ".strip() → "hello" |
lstrip() |
去除字符串左端的空白字符。 |
" hello ".lstrip() → "hello " |
rstrip() |
去除字符串右端的空白字符。 |
" hello ".rstrip() → " hello" |
zfill(width) |
在字符串左侧填充 0,直到字符串长度为 width。 |
"42".zfill(5) → "00042" |
center(width, fill) |
将字符串居中,并用 fill 字符填充到指定宽度。 |
"hello".center(10, "*") → "**hello***" |
| 分割与连接 |
|
|
split(sep) |
以 sep 为分隔符将字符串分割为列表。 |
"a,b,c".split(",") → ["a", "b", "c"] |
join(iterable) |
将可迭代对象中的元素用字符串连接起来。 |
",".join(["a", "b", "c"]) → "a,b,c"
"----".join("asdf") → a----s----d----f |
| 判断与检查 |
|
|
isalpha() |
检查字符串是否全部由字母组成。 |
"hello".isalpha() → True |
isdigit() |
检查字符串是否全部由数字组成。 |
"123".isdigit() → True |
isalnum() |
检查字符串是否由字母或数字组成。 |
"hello123".isalnum() → True |
isspace() |
检查字符串是否全部由空白字符组成。 |
" ".isspace() → True |
islower() |
检查字符串是否全部为小写。 |
"hello".islower() → True |
isupper() |
检查字符串是否全部为大写。 |
"HELLO".isupper() → True |