s = "Hello World"
print(s.upper()) # 输出:HELLO WORLD
print(s.lower()) # 输出:hello world
print(s.swapcase()) # 输出:hELLO wORLD
print(s.capitalize()) # 输出:Hello world
s = " Hello\t\n"
print(s.strip()) # 输出:"Hello"
print(s.lstrip()) # 输出:"Hello\t\n"
print(s.rstrip()) # 输出:" Hello"
s = "apple,banana,apple"
print(s.find("banana")) # 输出:6
print(s.rfind("apple")) # 输出:12
print(s.index("banana")) # 输出:6(未找到则报错)
s = "Hello Python"
print(s.replace("Python", "World")) # 输出:Hello World
print(s.removeprefix("Hello ")) # 输出:Python(Python 3.9+)
print(s.removesuffix("Python")) # 输出:Hello
s = "a,b,c"
print(s.split(",")) # 输出:['a', 'b', 'c']
print(s.partition(",")) # 输出:('a', ',', 'b,c')
print(s.rsplit(",", 1)) # 输出:['a,b', 'c']
lst = ["2025", "03", "01"]
print("-".join(lst)) # 输出:2025-03-01
print(s.center(20, "*")) # 输出:==****==*Hello Python==****==*
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("Python3".isalnum()) # True
print("hello".islower()) # True
s = "中文"
bytes_data = s.encode("utf-8") # b'\xe4\xb8\xad\xe6\x96\x87'
print(bytes_data.decode("gbk", errors="ignore")) # 忽略解码错误
print("42".zfill(5)) # 输出:00042
print("hello".ljust(10, "-")) # 输出:hello-----
print("world".rjust(10, "*")) # 输出:==****==*world
print("Hello\nWorld".expandtabs(4)) # 替换制表符为4空格
print(r"C:\new\test") # 原始字符串:C:\new\test
s = "apple banana apple"
print(s.count("apple")) # 输出:2
trans_table = str.maketrans("ae", "12")
print("apple".translate(trans_table)) # 输出:1ppl2
print(ord("A")) # 输出:65
print(chr(65)) # 输出:A
from string import Template
t = Template("$name今年$age岁")
print(t.substitute(name="Alice", age=25)) # 输出:Alice今年25岁
print("{:.2f}".format(3.1415)) # 输出:3.14
print(f"{255:#x}") # 输出:0xff
本文详细介绍了 Python 字符串的基本操作及常用方法,包括字符串的定义、索引、切片、常用的字符串方法(如大小写转换、查找替换、去空白字符等)、字符串格式化、编码解码方法、检查方法以及字符串的正则表达式操作。通过这些方法,Python 提供了强大的字符串处理能力,帮助开发者更加高效地处理文本数据。掌握这些基本操作对于 Python 编程是至关重要的,尤其在文本处理和数据解析中,能够显著提升代码的可读性和简洁性。