在 Python 中,字符串(str)是不可变的序列类型,提供了大量内置方法用于文本处理。以下是最常用的一些字符串函数及其使用示例。
str.strip([chars])
移除字符串首尾指定字符(默认为空白字符)。
# 示例
text = " Hello World! "
print(text.strip()) # 输出: "Hello World!"
str.split(sep=None, maxsplit=-1)
按分隔符拆分字符串,返回列表。
# 示例
data = "apple,banana,orange"
print(data.split(',')) # 输出: ['apple', 'banana', 'orange']
str.join(iterable)
将可迭代对象中的字符串用当前字符串连接。
# 示例
words = ['Python', 'is', 'awesome']
sentence = ' '.join(words)
print(sentence) # 输出: "Python is awesome"
str.replace(old, new[, count])
替换字符串中的子串。
# 示例
text = "Hello world"
new_text = text.replace("world", "Python")
print(new_text) # 输出: "Hello Python"
str.find(sub[, start[, end]])
查找子串位置,未找到返回 -1。
# 示例
s = "Learn Python today"
idx = s.find("Python")
print(idx) # 输出: 6
str.upper() / str.lower()
转换为全大写或全小写。
# 示例
text = "Hello"
print(text.upper()) # "HELLO"
print(text.lower()) # "hello"
str.startswith(prefix) / str.endswith(suffix)
判断字符串是否以指定前缀/后缀开头或结尾。
# 示例
filename = "report.pdf"
print(filename.endswith(".pdf")) # True