今さらPython3(8) - 文字列操作の続き
この本の第2章を引き続き読んでます。
- 作者: Bill Lubanovic,斎藤康毅,長尾高弘
- 出版社/メーカー: オライリージャパン
- 発売日: 2015/12/01
- メディア: 単行本(ソフトカバー)
- この商品を含むブログを見る
str()関数を使う
>>> str(98.6) '98.6' >>> str(1.0e4) '10000.0' >>> str(True) 'True' >>> >>> palindrome = 'A man,\nA plan,\nA canal:\nPanama.' >>> print(palindrome) A man, A plan, A canal: Panama. >>>
\nで改行。このあたりは、「安心してください。知ってますよ」って感じですね。
>>> print('\tabc') abc >>> print('a\tbc') a bc >>> print('ab\tc') ab c >>> print('abc\t') abc >>>
\tはタブを表すと。最後のヤツは視認できないけどね。
>>> test1mony = "\"I did nothing!\" he said. \"Not that either! Or the other thi ng.\"" >>> print(test1mony) "I did nothing!" he said. "Not that either! Or the other thing." >>> test1mony '"I did nothing!" he said. "Not that either! Or the other thing."' >>> >>> fact = "The world's largest rubber duck was 54'2\" by 67'7\" by 105'" >>> print(fact) The world's largest rubber duck was 54'2" by 67'7" by 105' >>> speech = 'Today we honor our friend, the backslash: \\.' >>> print(speech) Today we honor our friend, the backslash: \.
ダブルクオーテーション(")とかバックスラッシュ(\)自体をエスケープする場合はこれと。
文字列の足し算
>>> 'Release the kraken!' + 'At once!' 'Release the kraken!At once!' >>> "My word! " "A gentlemen caller!" 'My word! A gentlemen caller!' >>> a = "My word!" "A gentlemen caller!" >>> a 'My word!A gentlemen caller!'
文字列同士をプラス(+)でつなぐのは知ってたけど、ただ並べるだけで1つになっているのは意外。
>>> a = 'Duck.' >>> b = a >>> c = 'Grey Duck!' >>> a + b + c 'Duck.Duck.Grey Duck!' >>> print(a, b, c) Duck. Duck. Grey Duck!
最後に文字列のかけ算もできるよと。
>>> start = 'Na ' * 4 + '\n' >>> middle = 'Hey ' * 3 + '\n' >>> end = 'Goddbye.' >>> print(start + start + middle + end) Na Na Na Na Na Na Na Na Hey Hey Hey Goddbye. >>>
(つづく)