Pythonのメモ帳

numpy, pandas, tensorflow を使いこなすための忘備録

配列内の各要素に含まれる特定の文字列を置換・削除する方法

文字列の置換はreplace()を使う。

string = 'abcde'
string_new = string.replace('a', 'A')
print(string_new)

出力: 'Abcde'

 

これが使えるのは単独の文字列だけで、配列(各要素が文字列になっている配列)には使えない。

str_list = ['abcde','abcde']
str_list_new = str_list.replace('a', 'A')

これを処理しようとするとエラーになる。
AttributeError
: 'list' object has no attribute 'replace'

 

なので以下のように、配列を一旦単独の文字列に変換し、replace()で置換、のちに配列に戻すという処理をする。

str_list = ['abcde','abcde']
string = ",".join(str_list)
string_new = string.replace('a', 'A')
str_list_new =  string_new.split(",")
print(string_new)

出力: ['Abcde', 'Abcde']

 

ちなみに、このreplace()の2番目の引数を空白('')にしておけば、削除の処理ができる。

string_new = string.replace('a', '')

 

 

 WEB/EC専門の転職支援サービス【サポタント】