30
28

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 5 years have passed since last update.

【追記】複数スペースを含む文字列の分割のメモ

Last updated at Posted at 2015-12-03

複数のスペースを含む文字列の分割

例えば、次のような文字列を半角スペースで分割すると、複数の半角スペースが途中にある場合、空文字列が要素に含まれてしまう。

test1.py
time = "Dec  3 14:25:33"
words = time.split(" ")
print words #['Dec', '', '3', '14:25:33']

正規表現モジュールを用いることで解決。

test2.py
import re

time = "Dec  3 14:25:33"
words = re.split(" +", time)
print words #['Dec', '3', '14:25:33']

追記

コメントでご指摘をいただきましたが、splitの引数を省略すると、スペース・タブ・改行といった区切り文字で、空文字列が入ることなく分割できるようです。

参考

pythonの練習帳

30
28
2

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
30
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?