Pythonで文字列中にある特定の文字を別の文字を置き換えたい

Category :

文中の単語を別の単語に置き換える

text = 'I use a centos.'
translate_text = text.replace('centos', 'ubuntu')
print(translate_text)

結果

I use a ubuntu.

1文字を別の1文字に置き換える

下記のように'centos'の1文字1文字を別の1文字に置き換えていきます。 c→u e→b n→u t→n o→t s→u

text = 'I am centos.'
translate_text = text.translate(str.maketrans('centos', 'ubuntu'))
print(translate_text)

結果

I am ubuntu.

参考

https://orangain.hatenablog.com/entry/20100503/1272900555

TOP
© 2021 uichi