3
3

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.

文字列リテラルのリストはstr.split()を使うと短く書ける

Last updated at Posted at 2017-12-12

この記事は Pythonのコードを短く簡潔に書くテクニック Advent Calendar 2017 の13日目です。

はじめに

文字列リテラルのリストを作りたいときは、普通にリストを書くよりstr.split()を使うと短く書けます。

普通に書いた場合

>>> ['black', 'gray', 'white', 'red', 'green', 'blue']
['black', 'gray', 'white', 'red', 'green', 'blue']

str.split()を使った場合

str.split()は引数で指定したセパレータで文字列を分割しますが、省略した場合はスペースで分割してくれます。

>>> 'black gray white red green blue'.split()
['black', 'gray', 'white', 'red', 'green', 'blue']

スペースを含む文字列リテラルを作成したいときは、別の文字をセパレータとして使うと良いでしょう。

>>> 'Amazon Web Services|Google Cloud Platform|Microsoft Azure'.split('|')
['Amazon Web Services', 'Google Cloud Platform', 'Microsoft Azure']

参考

  • Python3 ドキュメント

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?