8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】AttributeError: 'list' object has no attribute 'replace'

Last updated at Posted at 2020-07-28

Pythonのスクレイピングを勉強中、値の加工をしていたらAttributeError: 'list' object has no attribute 'replace'が出たので、メモで対策を残します

エラーが出た原因

以下のように、 list (list型)から特定の文字列 a を削除するロジックを書きました。

list = ['aaabbb','article']

>>> list_replace = list.replace('a', '')
AttributeError: 'list' object has no attribute 'replace'

しかし、このエラー

AttributeError: 'list' object has no attribute 'replace'

対策

配列を一旦単独の文字列に変換してから、replace()で置換、のちに配列に戻すという処理をすればいいらしいです。

list = ['aaabbb','article']

>>> list_replace = [item.replace('a', '') for item in list]
>>> list_replace
['bbb', 'rticle']

参考
https://spcx8.hatenablog.com/entry/2017/07/05/204423

8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?