Search code examples
python-3.xlistfunctionfor-looplist-comprehension

Adding two items to a list in list commprehension


I wrote a for loop which adds the letters of the input into the list "words" and it also adds a space and then the letter if the letter is capital. Like so:

def solution(s):
    word = []
    for letter in s:
        print(letter.isupper())
        if letter.isupper():
            word.append(" ")
            word.append(letter)
        else:
            word.append(letter)
    return ''.join(word)

print(solution("helloWorld"))

output: hello World

I want to convert this to a list comprehension but it wont take both items I would like to add to the list, I tried the following:

def solution(s):
    word = [" " and letter if letter.isupper() else letter for letter in s]
    return ''.join(word)

print(solution("helloWorld"))

output: helloWorld

wanted output: hello World

How can I add the space along with the letter if it is an upper case, as done in the for loop?

EDIT:

Found out it can be done the following way.

def solution(s):
    word = [" " + letter if letter.isupper() else letter for letter in s]
    return ''.join(word)

Solution

  • The following code works:

    def solution(s):
        word = [f" {letter}" if letter.isupper() else letter for letter in s]
        return ''.join(word)
    
    print(solution("helloWorldFooBar"))
    

    result: hello World Foo Bar