Python 元组到字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3886669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tuple to string
提问by Dais
I have a tuple.
我有一个元组。
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
And I want to convert it to a string..
我想将其转换为字符串..
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
what is a good way to do this?
这样做的好方法是什么?
Thanks!
谢谢!
采纳答案by mechanical_meat
tst2 = str(tst)
E.g.:
例如:
>>> tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
>>> tst2 = str(tst)
>>> print tst2
([['name', u'bob-21'], ['name', u'john-28']], True)
>>> repr(tst2)
'"([[\'name\', u\'bob-21\'], [\'name\', u\'john-28\']], True)"'
回答by Stigma
While I like Adam's suggestion for str(), I'd be leaning towards repr()instead, given the fact you are explicitly looking for a python-syntax-like representation of the object. Judging help(str), its string conversion for a tuple might end up defined differently in future versions.
虽然我喜欢 Adam 对 的建议,但鉴于您正在明确寻找对象的类似 python 语法的表示这一事实str(),我会倾向于repr()这样做。判断help(str),它的元组字符串转换最终可能会在未来版本中定义不同。
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
...
As opposed to help(repr):
与help(repr):
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
In todays practice and environment though, there'd be little difference between the two, so use what describes your need best - something you can feed back to eval(), or something meant for user consumption.
但是,在当今的实践和环境中,两者之间几乎没有什么区别,因此请使用最能描述您的需求的东西 - 您可以反馈的eval()东西,或者用于用户消费的东西。
>>> str(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"
>>> repr(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"

