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
  • 12,329
  • 9
  • 33
  • 51
JokerMartini
  • 4,602
  • 3
  • 42
  • 128

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
  • 12,329
  • 9
  • 33
  • 51
1

You may avoid use isinstance

[x.lower() if type(x)==str else x for x in names]
mmachine
  • 804
  • 5
  • 9