溫馨提示×

python中怎么替換字符串

小億
280
2024-04-15 09:42:04
欄目: 編程語言

在Python中,字符串是不可變的,因此無法直接修改字符串中的字符。但是可以通過一些方法來替換字符串中的特定子串,比如使用replace()方法或者使用正則表達式。下面是一些常用的方法:

  1. 使用replace()方法:
s = "Hello, world!"
new_s = s.replace("world", "Python")
print(new_s)  # Output: Hello, Python!
  1. 使用正則表達式:
import re
s = "Hello, world!"
new_s = re.sub(r'world', 'Python', s)
print(new_s)  # Output: Hello, Python!
  1. 使用字符串切片:
s = "Hello, world!"
index = s.find("world")
new_s = s[:index] + "Python" + s[index+len("world"):]
print(new_s)  # Output: Hello, Python!

這些方法都可以用來替換字符串中的特定子串,具體使用哪種方法取決于具體的需求和情況。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女