Pythonでは、文字列の末尾を置換する方法が2つあります。
スライスを使う方法
まず、「+」の左辺に文字列を「[:-1]」でスライスした結果を指定します。そして、「+」の右辺に置換後の文字列を指定します。
# text=対象の文字列, new=置換後の文字列
text = "Hello,World"
new = "*"
result = text[:-1] + new
print(result) # 出力:Hello,Worl*
sub()を使う方法
もうひとつは、sub()
を使う方法です。まず、re
をインポートします。次に、re.sub()
の第1引数に「r”.$”」、第2引数に置換後の文字列を指定します。
import re
# text=対象の文字列, new=置換後の文字列
text = "Hello,World"
new = "?"
result = re.sub(r".$", new, text)
print(result) # 出力:Hello,Worl?
これらの方法を使えば、Pythonで文字列の末尾を簡単に置換することができます。