Python Check if string change succeeded

I split the string "name:john" and want to check if the split has occurred or not. What is the correct way to check?

Quick fix: (but maybe brute force)

 name = "name:john" splitted = name.split(":") if len(splitted) > 1: print "split" 

Is there a more sophisticated way to check?

+6
source share
2 answers

You can also select EAFP : split, unzip and handle a ValueError :

 try: key, value = name.split(":") except ValueError: print "Failure" else: print "Success" 
+9
source

Why not use the in operand?

 if ':' in name: print "split" 

Or, if you want to : preset between the last and final character, you can do:

 if ':' in name[1:-1]: print "split" 
+3
source

All Articles