72
65

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.

文字列を1文字ずつのリストにする

Last updated at Posted at 2019-05-08

PerlとPythonの比較

Perlならsplit()で一発。(Rubyも同じらしい)

Perl
use Data::Dumper;
print Dumper split(//, '日月火水木金土');
# =>
#   $VAR1 = '日';
#   $VAR2 = '月';
#   $VAR3 = '火';
#   $VAR4 = '水';
#   $VAR5 = '木';
#   $VAR6 = '金';
#   $VAR7 = '土';

Pythonだと、split()に空文字を渡してもうまくいかない。

Python
print('日月火水木金土'.split())
# => ['日月火水木金土']

print('日月火水木金土'.split(None))
# => ['日月火水木金土']

print('日月火水木金土'.split(''))
# => ValueError: empty separator

正解はこちら。list()で一発。

Python
print(list('日月火水木金土'))
# => ['日', '月', '火', '水', '木', '金', '土']

こういうのがやりたかった

Perl
print join ',', map { qq|"$_"| } split(//, '日月火水木金土');
# => "日","月","火","水","木","金","土"
Python
print(','.join(map(lambda x: '"{}"'.format(x), list('日月火水木金土'))))
# => "日","月","火","水","木","金","土"

print(','.join(map(lambda x: '"{}"'.format(x), '日月火水木金土')))
# => "日","月","火","水","木","金","土"

print(*map(lambda x: '"{}"'.format(x), '日月火水木金土'), sep=',')
# => "日","月","火","水","木","金","土"

文字列や配列の考え方が根本的に違う?
文字列をsplit()で配列にするというより、文字列自体が文字配列に近い形で扱われているという印象。

72
65
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
72
65

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?