Home > Enterprise >  Adding two items to a list in list commprehension
Adding two items to a list in list commprehension

Time:12-03

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)

CodePudding user response:

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

  • Related