开发者

python: How to determine if a string contains a tuple?

I need a clean way to determine if a string is actually a tuple, like so:

'(123,456)' --> True

'hello world' --> False

I can think of two ways to do this:

开发者_开发问答
  1. a regex
  2. call eval and catch/ignore a SyntaxError

I don't like the second option. I'm fine with the first option but just wanted to know if there was a better way to do it.

Thanks.


def represents_tuple(s):
    try: return type(ast.literal_eval(s)) == tuple
    except SyntaxError: return False
    except ValueError: return False


If the tuple inside the string can only have simple numbers, then use a regex. If the tuple members can be arbitrarily complex (such as nested lists), use eval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜