Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: apply lower() strip() and split() in one line

In python, what's the fastest way to define variables from splitting a string, but also converting to lowercase and striping white spaces?

Some thing like

args.where = 'Sn = Smith'
a,v = args.where.lower().split('=').strip()
like image 558
RASG Avatar asked Sep 24 '26 10:09

RASG


1 Answers

You are splitting a string into a list, and you can't strip the list. You need to process each element from the split:

a, v = (a.strip() for a in args.where.lower().split('='))

This uses a generator expression to process each element, so no intermediary list is created for the stripped strings. Python will throw an exception here if the expression doesn't produce exactly two values.

To focus on speed in this case is.. pointless, unless you are doing this on a very large body of elements. You can micro-optimise the above with map(), though:

a, v = map(str.strip, args.where.lower().split('='))

but the cost in readability may just not be worth it, not for just 2 elements.

like image 140
Martijn Pieters Avatar answered Sep 26 '26 01:09

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!