LoginSignup
2
2

More than 5 years have passed since last update.

perl使いのpythonメモ - join

Last updated at Posted at 2016-10-04
  • pythonのjoinであれ?とおもったのでメモしときます。

数字をjoinしたらエラー

  • 年月日を文字列にするイメージです。"2016/4"がほしい値です。
>>> ym = [2016,4]
>>> "/".join(ym)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

  • エラーになりました。文字列で連結しろよってことですね。

文字列に変換

  • mapで文字列に変換します。
>>> ym = [2016,4]
>>> "/".join(map(lambda x:str(x),ym))
'2016/4'
  • 欲しい形になりました。

桁揃え

  • monthの部分を0埋めしたいとおもいます。"2016/04"がほしい値です。
>>> ym = [2016,4]
>>> "/".join(map(lambda x:(u"%02d"%x),ym))
'2016/04'

perlなら...

  • こんな感じですかね。0埋めしないのならperlのほうが簡単ですね。
% perl -le 'my @ym = (2016,4);print join("/",@ym)'
2016/4

% perl -le 'my @ym = (2016,4);print join("/",map {sprintf("%02d",$_)}@ym)'
2016/04
2
2
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
2
2