python - Empty space check and string.split error -
i have following error when try split string 2 values.
error: builtins.valueerror: need more 1 value unpack
when debug, shows first if statement still true, when there no space in string. wondering why not going second if statement.
if ('' in line): line=line.strip('\n') code,number=line.split() print(code,number) if '' not in line: print('missing key')
'' in anystring true because it's empty string. empty string going in every single possible string, empty set subset of every set. mean check ' ' single space character.
a better approach split string on whitespace , check length of list determine if have 2 items. example:
linesplit = line.split() if len(linesplit) == 2: code, number = linesplit print(code, number) else: print('missing key') this method before leap (lbyl).
try: code, number = line.split() print(code, number) except valueerror: print('missing key') and alternative method ask forgiveness rather permission (eafp).
by way, took out calls str.strip, because using str.split takes care of you.
Comments
Post a Comment