Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Check if String split succeeded

Tags:

python

string

I am splitting a string "name:john" and want to check whether the split happened or not. What is the right way doing that check?

A quick solution: (but maybe overkill)

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

Is there a more elaborate way of doing the check?

like image 292
user1767754 Avatar asked Aug 10 '15 17:08

user1767754


1 Answers

You can also choose the EAFP approach: split, unpack and handle ValueError:

try:
    key, value = name.split(":")
except ValueError:
    print "Failure"
else:
    print "Success" 
like image 166
alecxe Avatar answered Sep 20 '22 20:09

alecxe