當前位置: 妍妍網 > 碼農

Python如何「從迪迦阿特曼轉變成山姆·阿特曼?」——10種文本替換例項

2024-03-10碼農

Python,學霸

方法1:replace

# 打印 Hello World
text = "迪迦阿特曼"
new = text.replace("迪迦""山姆·")
print(new)

方法2:sub方法

import re
text = "迪迦阿特曼"
new_text = re.sub(r'迪迦''山姆·', text)
print(new_text)

方法3:format方法

text = "迪迦阿特曼"
new_text = "山姆· {}".format(text.split('迪迦')[1])
print(new_text)

方法4:partition方法

text = "迪迦阿特曼"
before, _, after = text.partition('迪迦')
new_text = '山姆·' + after
print(new_text)

方法5:split方法

text = "迪迦阿特曼"
parts = text.split('迪迦')
new_text = '山姆·'.join(parts)
print(new_text)

方法6:subn方法

import re
text = "迪迦阿特曼"
new_text, _ = re.subn('迪迦''山姆·', text)
print(new_text)

方法7:compile方法

import re
text = "迪迦阿特曼"
pattern = re.compile('迪迦')
new_text = pattern.sub('山姆·', text)
print(new_text)

方法8:find方法

text = "迪迦阿特曼"
index = text.find('迪迦')
new_text = text[:index] + '山姆·' + text[index + len('迪迦'):]
print(new_text)

方法9:startswith

text = "迪迦阿特曼"
if text.startswith('迪迦'):
new_text = '山姆·' + text[len('迪迦'):]
print(new_text)

方法10:直接法

text="迪迦阿特曼"
text="山姆·阿特曼"
print(text)

使用 replace 方法是最直接的替換方式,適合用於簡單的字串替換。

re.sub 方法使用正規表式進行替換,適合處理復雜的替換邏輯。format 方法和 partition 方法都可以用來處理特定位置的替換,適合處理需要根據位置進行替換的情況。

split 方法可以將字串拆分成列表,然後再進行合並,適合處理需要對字串進行分割再合並的情況。

subn 方法和 compile 方法同樣適合處理復雜的替換邏輯,尤其適合處理需要多次替換的情況。

find 方法和 startswith 方法可以用來尋找指定字串的位置,再進行替換操作。直接賦值法可以直接對字串進行賦值替換。