Memoize |
BasicWerk
EC Support
Technique
Facebook
|
20141208195231_Python_string_syntax_format_print |
|
Python_string_syntax_format_print
Python ではダブルクォーテーションとシングルクォーテーションで特殊文字の展開に差はない。
>>> print("foo\tbar")
foo bar
>>> print('foo\tbar')
foo bar
エスケープ文字をそのまま印字するには r["']...["'] を使う。 r は row 文字の略。 >>> print(r"foo\tbar") foo\tbar
文字列内で改行する場合はトリプルクォーテーションを使う。
>>> print("""foo
... bar""")
foo
bar
>>> print('''foo
... bar''')
foo
bar
フォーマット文字列。
# '%format' % (tuple)
>>> 'No.%d: %s' % (1, 'First Man')
'No.1: First Man'
# '%format' % {dict}
>>> d = {"id":32, "name":"First Man", "age":36}
>>> "id:%(id)05d name+id:%(name)s_%(id)d age:%(age)03d" % d
'id:00032 name+id:First Man_32 age:036'
print() 関数の制御。 >>> str = '''My name is Prince. ... And I'm funky. ... ''' # default は end='\n' >>> print(str, end='') My name is Prince. And I'm funky. >>> str2 = "One and only." # default は sep=' ' >>> print(str, str2, sep='', end='\n') My name is Prince. And I'm funky. One and only.
|
| © Shin Nakamura/BasicWerk 2008 - 2014 |