1
2

More than 3 years have passed since last update.

【Python】文字列の特定の文字を別の文字で置き換える

Last updated at Posted at 2021-02-18

例えば、abcdeの3番目cxで置き換えた文字列(abxed)が取得したい時。

方法は3つ。

  1. strを一度、listにしてから置き換える
  2. 置き換える文字の前後をsliceで取得し、結合する
  3. 文字の重複がない場合はreplaceで置き換える

strを一度、listにしてから置き換える

strのまま指定位置を置き換えようとするとエラー

>>> s = 'abcde'
>>> s[2] = 'x'
Traceback (most recent call last):
  File "Main.py", line 2, in <module>
    s[2] = 'x'
TypeError: 'str' object does not support item assignment

だから、一度listにしてから置き換える

>>> l = list('abcde')
>>> print(l)
>>> l[2] = 'x'
>>> print(l)
['a', 'b', 'c', 'e', 'd']
['a', 'b', 'x', 'e', 'd']
>>> print("".join(l))
'abxde'

この方法で、リストデータの内容を書き換え、文字を置き換えた新たな文字列を作り出せる。

置き換える文字の前後をsliceで取得し、結合する

>>> s = 'abcde'
>>> print(s[:2] + 'x' + s[3:])
'abxde'

この方法でも、文字を置き換えた新たな文字列を作り出せる。
個人的にはこっちの方が好き。

文字の重複がない場合はreplaceで置き換える

例のように cx でというように置き換えたい文字が特定できており、かつその文字が1度しか登場しない場合は、replace で置き換えられる。

>>> s = 'abcde'
>>> s = s.replace('c', 'x')
>>> print(s)
'abxde'

ただし、abaade など a が何度も現れるような文字列では全ての a が置き換わってしまうので注意。
@dfghdfdjftyfghvgjhk さんありがとうございます。

参考文献

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2