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:
开发者_开发问答- a regex
- 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.
精彩评论