8
14

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 配列内の文字列の一括置換

Posted at

スクレイピングをしていて取得した文字列を配列に格納したとき
配列内の余分な改行が・・・
そんな時に置換 or 削除したいなって場面に遭遇したので
備忘録の意味も込めて

#やりたい事

str_list = ['あい\nうえお', 'かいくけこ', 'さし\nすせ\n', 'たちつて\n', 'なに\n\n\n']
str_list2 = [['あい\nうえお', 'かいくけこ'], ['さし\nすせ\n', 'たちつて\n', 'なに\n\n\n'], ['はひふ\nへほ', '\nみむめも\n'], ['やゆよ'], ['らり\nるれろ', 'わをん']]

こんな感じでスクレイピングしていると欲しい文字列以外が含まれていたりする

これを簡素にしたい

普通
replace_list = []
for s in str_list:
    if '\n' in s:
        text = s.replace('\n', '')
        replace_list.append(text)
    else:
        replace_list.append(s)

print(replace_list)
>>['あいうえお', 'かいくけこ', 'さしすせそ', 'たちつてと', 'なにぬねの']

for i in str_list2:
    for s in i:
        if '\n' in s:
            text = s.replace('\n', '')
            replace_list2.append(text)
        else:
            replace_list2.append(s)
    replace_list3.append(replace_list2)
    replace_list2 = []

print(replace_list3)
>>[['あいうえお', 'かいくけこ'], ['さしすせそ', 'たちつてと', 'なにぬねの'], ['はひふへほ', 'まみむめも'], ['やゆよ'], ['らりるれろ', 'わをん']]

####簡素にできた

内包表記
replace_list = [s.replace('\n', '') for s in str_list]
replace_list2 = [[s.replace('\n', '') for s in text] for text in str_list2]

print(replace_list)
print(replace_list2)
>>['あいうえお', 'かいくけこ', 'さしすせそ', 'たちつてと', 'なにぬねの']
>>[['あいうえお', 'かいくけこ'], ['さしすせそ', 'たちつてと', 'なにぬねの'], ['はひふへほ', 'まみむめも'], ['やゆよ'], ['らりるれろ', 'わをん']]

内包表記を使っただけだけどこっちのほうがぽい

8
14
0

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
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?