1. 字符串连接与格式化在Python中,字符串连接可以使用加号 + 实现基本连接,而格式化字符串则可以通过 操作符或者 fstring 来完成。使用 操作符格式化字符串name quot;Al...
在Python中,字符串连接可以使用加号 + 实现基本连接,而格式化字符串则可以通过 % 操作符或者 f-string 来完成。
% 操作符格式化字符串name = "Alice"
age = 25
formatted_name = "My name is %s and I am %d years old." % (name, age)
print(formatted_name)name = "Alice"
age = 25
formatted_name = f"My name is {name} and I am {age} years old."
print(formatted_name)字符串切片允许你从字符串中提取一部分字符。语法为 string[start:end:step]。
text = "Hello, World!"
print(text[0:5]) # 输出: Hello
print(text[7:]) # 输出: World!可以使用 find() 和 replace() 方法来查找和替换字符串中的内容。
text = "Hello, World!"
print(text.find("World")) # 输出: 7
print(text.replace("World", "Python")) # 输出: Hello, Python!Python提供了多种方法来转换字符串的大小写。
text = "Hello, World!"
print(text.upper()) # 输出: HELLO, WORLD!
print(text.lower()) # 输出: hello, world!
print(text.title()) # 输出: Hello, World!
print(text.capitalize()) # 输出: Hello, world!可以使用 strip(), lstrip(), 和 rstrip() 方法来去除字符串两端的空白字符。
text = " Hello, World! "
print(text.strip()) # 输出: Hello, World!
print(text.lstrip()) # 输出: Hello, World!
print(text.rstrip()) # 输出: Hello, World!这些技巧可以帮助你在Python中进行高效的字符串操作,提高代码的可读性和效率。