I'm creating a tuple from a string as demonstrated below.
line = 'StartupGrind , 26\n' #string
w,f=line.strip().split(',') #get a tuple
w,f= (w.strip(),int(f.strip())) #make it string,int
Can it be accomplished in a single line?
I'm creating a tuple from a string as demonstrated below.
line = 'StartupGrind , 26\n' #string
w,f=line.strip().split(',') #get a tuple
w,f= (w.strip(),int(f.strip())) #make it string,int
Can it be accomplished in a single line?
Don't try to do everything in one line, your task is actually not a good example for one line code, incline to more readable and maintainable code. Though here is a one liner and it's very readable:
w, f = (int(e) if e.strip().isdecimal() else e.strip() for e in line.split(','))
Use a one-liner only if it makes your solution better. Looks like a one-liner makes it more difficult to understand what the algorithm does.
Therefore, stay with two lines, but get rid off all unneeded .strip()
calls and parentheses:
w, f = line.split(',')
w, f = w.strip(), int(f)
This has the fewest characters and seems to be the most readable.
It's not one line like you seem to desire, but works well and is readable.
linesplit = line.strip().split(' , ')
w, f = linesplit[0], int(linesplit[1])
If you aren't sure whats going on here, strip
removes the \n
, split(' , ')
will create a list ['StartupGrind', '26']
, and the second line sets w to 'StartupGrind
and f to 26
.
If you really wanted this in one line I suppose this would work:
w, f = line.split(' , ')[0], int(line.strip().split(' , ')[1])
You should prefer 2-lines variant from @Mike Müller's answer:
w, f = line.split(',')
w, f = w.strip(), int(f)
Here's yet another one-liner, not recommended:
[(w, f)] = [(word.strip(), int(n)) for word, n in [line.split(',')]]
Here is a one line answer
w,f = map(lambda x: int(x) if x.strip().isdigit() else x, 'StartupGrind , 26\n'.strip().split(','))
I don't know if this helps. But you could try this.
w,f = line[:line.index(',')], int(line[line.index(',')+1:].strip())