Python: Apply Lower() Strip() and Split() in One Line

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()
0

4 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.

What you need is List comprehensions, here's and example that solves your problem.

args.where = 'Sn = Smith'
a,v = [val.strip() for val in args.where.lower().split('=')]
2

If you want to use strip() after you use split() (creating a list), you can use a generator expression.

where = 'Sn = Smith'
a, v = (word.strip() for word in where.lower().split('='))
0

If you have all string in your variable , you can use re

import re

word="Sn = Smith"
regex = r'\b\w+\b'
word1,word2=re.findall(regex,word.lower())
print (word1)
print("--")
print(word2)

OUTPUT :

sn
--
smith

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.