在python中用引号包装字符串的优雅方法是什么?

时间:2014-10-15 09:53:43

标签: python string

我只能想到两种方式,但在我看来,它们并非没有优雅的地方

"'" + 'hello' + "'"

"'%s'" % 'hello'

任何人都可以分享更好的方式吗?

2 个答案:

答案 0 :(得分:4)

您可以使用其repr表示。

>>> s = 'hello'

使用旧式格式

>>> print '%r' % s
'hello'

使用新式格式

>>> print '{!r}'.format(s)
'hello'

答案 1 :(得分:0)

使用三重引号。

>>> s='''This is a string containing "quoted words. Nice, isn't it?"'''
>>> print s
This is a string containing "quoted words. Nice, isn't it?"