0

Here's a list comprehension with a for loop to convert all characters to uppe case

string = 'Hello'
print "".join([s.upper() for s in string])

Here's a list comprehension to only convert the lower characters to upper case

print "".join([s.upper() for s in string if s.islower()])

Can there be a list comprehension that can swap the case in a string? Something like

print "".join([s.upper() for s in string if s.islower() else s.lower()])
Varun Verma
  • 704
  • 2
  • 10
  • 20
  • 1
    Are you looking for `s.swapcase()`? – Sayse Jul 03 '19 at 12:05
  • 1
    Yes, swapcase. But that's just an example I picked. Wanting to know if i can use a for loop, if and else within a list comprehension – Varun Verma Jul 03 '19 at 12:06
  • `list comprehension to only convert the lower characters to upper case` - NOPE. It's a list comprehension that only takes lower characters and convert them. "Hello" becomes "ELLO". `if` is a filter in list comprehension – h4z3 Jul 03 '19 at 12:08
  • Also for Python's ternary syntax check: https://docs.python.org/3/reference/expressions.html#conditional-expressions – orangeInk Jul 03 '19 at 12:08

2 Answers2

4

all you need is string.swapcase()

Mike Mint
  • 145
  • 5
3

Here's how you could do so using a list comprehension. Note that when you include both if/else, what is known as a ternary operator, the syntax must be as follows:

condition_if_true if condition else condition_if_false

Hence in this case, you can do:

string = 'Hello'

"".join([s.upper() if s.islower() else s.lower() for s in string])
# 'hELLO'
yatu
  • 86,083
  • 12
  • 84
  • 139
  • 1
    Thanks. That's exactly what I was looking for. Syntax for using for loop, if/else within a list comprehension – Varun Verma Jul 03 '19 at 12:08