0

Is there a way to write a one-liner which converts strings to lowercase and leaves numbers alone? So far I have this:

names = ["a","Abc","EFG",45,65]
newlist = [n.lower() for n in names if isinstance(n, basestring)]
print newlist 

>>>['a', 'abc', 'efg']

I would like this

>>>['a', 'abc', 'efg', 45 ,65]
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

2 Answers2

2

Use a conditional expression. You were filtering out non-strings.

Conditional expression: x if condition else y. Return x if condition is True, otherwise return y.

names = [n.lower() if isinstance(n, basestring) else n for n in names]
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
1

You may avoid use isinstance

[x.lower() if type(x)==str else x for x in names]
mmachine
  • 896
  • 6
  • 10