【问题标题】:Tuple to string元组到字符串
【发布时间】:2010-10-07 23:28:06
【问题描述】:

我有一个元组。

tst = ([['name', u'bob-21'], ['name', u'john-28']], True)

我想把它转换成一个字符串..

print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"

有什么好的方法可以做到这一点?

谢谢!

【问题讨论】:

    标签: python


    【解决方案1】:
    tst2 = str(tst)
    

    例如:

    >>> 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)"'
    

    【讨论】:

    • 谢谢亚当。我想过使用 str 但从没想过它会起作用!
    【解决方案2】:

    虽然我喜欢 Adam 对 str() 的建议,但我更倾向于 repr(),因为您明确地在寻找对象的类似 python 语法的表示。判断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.
     ...
    

    相对于help(repr)

    repr(...)
        repr(object) -> string
    
        Return the canonical string representation of the object.
        For most object types, eval(repr(object)) == object.
    

    不过,在今天的实践和环境中,两者之间几乎没有区别,因此请使用最能描述您需求的内容 - 您可以反馈给 eval() 的内容,或者供用户使用的内容。

    >>> str(tst)
    "([['name', u'bob-21'], ['name', u'john-28']], True)"
    >>> repr(tst)
    "([['name', u'bob-21'], ['name', u'john-28']], True)"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多