karlxu
V2EX  ›  问与答

python 字符串如何转元祖?试了 tuple()不是我想要的格式。。。

  •  
  •   karlxu · Mar 16, 2016 · 3958 views
    This topic created in 3907 days ago, the information mentioned may be changed or developed.
    有个字符串:
    s='(u'22222', u'b.b.com', u'test3', u'127.0.0.1,c.c.com')(u'33333', u'c.c.com', u'test1', u'127.0.0.1,c.c.com')(u'f1', u'a.a.com', u'test2', u'127.0.0.1,a.a.com')'

    试了用 tuple(s)来转,结果如下:



    我想要的是这种:是 s[0]=(u'22222', u'b.b.com', u'test3', u'127.0.0.1,c.c.com')
    有什么快捷的方法吗?谢谢了!
    8 replies  •  2016-03-16 14:29:20 +08:00
    wizardforcel
    wizardforcel
    Mar 16, 2016 via Android
    1
    这种情况真得 eval 了。。。
    karlxu
    karlxu
    OP
    Mar 16, 2016
    2
    @wizardforcel 你好,我试了你说的 eval ,提示 TypeError: 'tuple' object is not callable,好像也不行。我是直接 b = eval(s),然后 print b
    hahastudio
    hahastudio
    Mar 16, 2016❤️1
    3
    [eval(p+')', {}) for p in s.split(')') if p]
    imn1
    imn1
    Mar 16, 2016❤️1
    4
    用正则转 json , parse ,然后……
    或者
    拆字符串为列表,然后……
    ToughGuy
    ToughGuy
    Mar 16, 2016❤️1
    5
    from ast import literal_eval

    s = literal_eval("(u'22222', u'b.b.com', u'test3', u'127.0.0.1,c.c.com'),(u'33333', u'c.c.com', u'test1', u'127.0.0.1,c.c.com'),(u'f1', u'a.a.com', u'test2', u'127.0.0.1,a.a.com')")
    weyou
    weyou
    Mar 16, 2016❤️1
    6
    >>> s="(u'22222', u'b.b.com', u'test3', u'127.0.0.1,c.c.com')(u'33333', u'c.c.com', u'test1', u'127.0.0.1,c.c.com')(u'f1', u'a.a.com', u'test2', u'127.0.0.1,a.a.com')"
    >>> s = [eval('({})'.format(item)) for item in s.strip('()').split(')(')]
    >>> s
    [('22222', 'b.b.com', 'test3', '127.0.0.1,c.c.com'), ('33333', 'c.c.com', 'test1', '127.0.0.1,c.c.com'), ('f1', 'a.a.com', 'test2', '127.0.0.1,a.a.com')]
    karlxu
    karlxu
    OP
    Mar 16, 2016
    7
    谢谢大家!感谢已发送~~~~
    weyou
    weyou
    Mar 16, 2016❤️1
    8
    最简单的:
    s = eval(s.replace(')(', '),('))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1023 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 22:46 · PVG 06:46 · LAX 14:46 · JFK 17:46
    ♥ Do have faith in what you're doing.