Home > database >  How to print the (word) in capital letters and with a space inbetween using a function?
How to print the (word) in capital letters and with a space inbetween using a function?

Time:10-06

I cannot figure this out for the life of me. I keep making queries that print only the first letter capitalized, the first letter the word, etc

I am wanting output that looks like: T H I S

This is my code, and it has to be a function (and the word is defined later)

    def add_space_and_capitalize(word):
for letter in word:
    new_word = ' '   letter.upper()
    return new_word

CodePudding user response:

You can alternatively convert the string to a list which can be iterated in the same way but then the .join() method can be used where " " is the separator. This also avoids the space at the start that other methods may cause. Hope this helps :)

def add_space_and_capitalize(word):
    chars=list(word)
    for i in range(len(chars)):
        chars[i]=chars[i].upper()
    new_word= " ".join(chars)
    return new_word

CodePudding user response:

you need to create a variable before the for loop instead of creating a new variable when the loop is running, because you are losing your last value that you stored

def add_space_and_capitalize(word):
    new_word = ""
    for letter in word:
        new_word  = ' '   letter.upper()
    return new_word
    
print(add_space_and_capitalize('this'))

OUTPUT

T H I S

CodePudding user response:

You can solve this by assigning an empty string inside the function and adding the uppercase letters inside the empty string to make all the letters uppercase with a space.

The function is as follows:

def add_space_and_capitalize(word):
   return_string = ""
   for letter in word:
     return_string  = str(letter.upper())   " "
   return return_string

message = 'python is fun' ## Provide a string
print(add_space_and_capitalize(message))

This will output the following:

P Y T H O N I S F U N

Hope this helps.

  • Related