共計 490 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,字符串是不可變的,因此無法直接修改字符串中的字符。但是可以通過一些方法來替換字符串中的特定子串,比如使用 replace()
方法或者使用正則表達式。下面是一些常用的方法:
- 使用
replace()
方法:
s = "Hello, world!"
new_s = s.replace("world", "Python")
print(new_s) # Output: Hello, Python!
- 使用正則表達式:
import re
s = "Hello, world!"
new_s = re.sub(r'world', 'Python', s)
print(new_s) # Output: Hello, Python!
- 使用字符串切片:
s = "Hello, world!"
index = s.find("world")
new_s = s[:index] + "Python" + s[index+len("world"):]
print(new_s) # Output: Hello, Python!
這些方法都可以用來替換字符串中的特定子串,具體使用哪種方法取決于具體的需求和情況。
丸趣 TV 網 – 提供最優質的資源集合!
正文完