开发者

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

开发者 https://www.devze.com 2023-02-19 15:15 出处:网络
I need a clean way to determine if a string is actually a tuple, like so: \'(123,456)\' --> True \'hello world\' --> False

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

精彩评论

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

关注公众号