+ [3,count,len](#3countlen_38)
一,常见方法
因为这些方法和其他的序列极其类似,所以在这里我不做过多介绍,只举出几个示例供大家回顾
1,下标索引
str = "Hello world!"
print(f"{str[0]},{str[-1]}") # 打印第一个元素和最后一个元素
# 输出结果:H,!
2,index
s = "你好,世界!"
# 使用index()方法获取字符串中指定字符的索引
index_of_char = s.index('好')
print(index_of_char) # 输出: 1
# 使用index()方法获取字符串中指定子串的索引
index_of_substring = s.index('你好')
print(index_of_substring) # 输出: 0
3,count,len
count
用来统计某元素出现的次数,len
用来计算字符串的长度:
str = "Hello world!"
# 使用count统计“o”出现的次数
print(str.count("o")) # 输出:2
#使用len计算长度
print(len(str)) # 输出:12
二,replace()
replace()
用于在字符串中查找所有指定的子字符串,并使用指定的替换字符串替换它们。
(注意:不会对原始字符串进行修改,而是返回一个替换好的新字符串)
基本语法:
str.replace(old, new, [count])
old
:要被替换的子字符串。
new
:用于替换的新子字符串。
count
:(可选)指定要替换的最多old
子字符串的个数。如果未指定或为负数,则替换所有出现。
示例:
text = "Hello, world!"
new_text = text.replace("world", "Python")
print(new_text) # 输出 "Hello, Python!"
三,split()
split()
方法:用于将一个字符串分割成一个字符串列表
(注意:不会修改原始字符串,而是返回一个新的列表)
基本语法:
str.split(separator, maxsplit)
separator
:指定用作分割符的子字符串。默认是一个空格。
maxsplit
:(可选)指定要分割的次数。默认是 -1,意味着分割所有出现。
示例:
text = "Python is fun"
words = text.split(" ")
print(words) # 输出 ['Python', 'is', 'fun']
text = "apple,banana,orange,grape"
fruits = text.split(",")
print(fruits) # 输出 ['apple', 'banana', 'orange', 'grape']
四,strip()
strip()
方法:用于删除字符串开头和结尾的指定字符
(注意:不会修改原始字符串,而是返回一个新的字符串)
基本语法:
strip([chars])
chars
:可选参数,表示需要删除的字符。如果未提供此参数,则默认删除空格。
(在 Python 的strip()
方法中,回车符(\r
)和换行符(\n
)都属于空格的一种形式,都会被默认删除。)
示例:
# 不提供chars
s = " Hello, World! "
s = s.strip()
print(s) # 输出:Hello, World!
# 提供chars:","
s = ",,Hello, World!,"
s = s.strip(",")
print(s) # 输出:Hello, World!
# 提供字符串:“12”
str = "12hello world21"
new_str = str.strip("12")
print(new_str) # 输出:hello world