问题: 解释 Python 中可用来修改字符串的方法和技术。举例说明如何执行常见的字符串操作,如连接、切分、替换和大小写字母转换。
解决方案: Python 提供了各种修改字符串的方法和技术。
下面是一些常见的操作:
合并: 可以使用 + 操作符合并两个或多个字符串。
str1 = "Hello"
str2 = " World"
result = str1 + str2
print(result) # "Hello World"

切片: 可以使用切片提取字符串的一部分。切片使用[start:end]格式,其中start为包容性格式,end为排他性格式。
text = "Python is awesome"
sliced = text [7:10]
print (sliced) # "is "

大写和小写: 使用 upper() 和 lower() 方法可以将字符串转换为大写或小写。
word = "Hello"
upper_word = word. upper ()
lower_word = word. lower ()
print (upper_word) # "HELLO"
print (lower_word) # "hello"

字符串插值: 使用 f-strings (Python 3.6+) 可以通过插入变量来修改字符串。
word = "Hello"
upper_word = word.upper ()
lower_word = word.lower ()
print (upper_word) # "HELLO"
print (lower_word) # "hello"

替换: 使用 replace() 方法可以替换字符串中的子串。
sentence = "I love programming in Python. "
modified = sentence.replace ("Python", "Java")
print (modified) # "I love programming in Java."

删除空白: 可以使用 strip()、Istrip() 和 rstrip 删除前导和尾部空白。
text = " This is a sentence with whitespace."
stripped_text = text.strip()
print (stripped_text) # "This is a sentence with whitespace.
