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()
で配列にするというより、文字列自体が文字配列に近い形で扱われているという印象。