0
0

More than 3 years have passed since last update.

pythonのforの改行を削除する

Posted at

pythonでスクレイピングプログラムを書いている際に.txtファイルから文字を読み込みたい際につまずいた点があったので残します

sample.txt
soccer
baseball
word
excel
point
address
japan
amazon
mac
apple
iphone
starbucks

このような.txtファイルがあったとします

sample.py
with open('word.txt', encoding='shift_jis') as keywords:
    for keyword in keywords:
        print(keyword)

このような形でキーワードの読み込みを行い出力をした際に当然上記のファイルのような出力結果を期待していたのですが

soccer

baseball

word

excel

point

address

japan

amazon

mac

apple

iphone

starbucks

このような形で出力されていました。中に改行文字が含まれていたのですね。

pythonの.strip()というメソッドが空白文字(ここでは改行)を打ち消してくれるのでこのようにしました

sample.py
with open('word.txt', encoding='shift_jis') as keywords:
    for word in keywords:
        keyword = word.strip()
        print(keyword)

そうすると出力結果は最初に読みこんだ.txtファイルと同じような期待していた出力結果になりました。
python初めて触ったのですが便利なメソッドが多くていいなと個人的に思ったのでこれから趣味レベルで触っていこうと思います

0
0
3

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
0
0