简体   繁体   中英

Add spaces in-between each letter in string, then not have space at the end

how would i create a program where you can add spaces in-between each letter in the string and then not have a space at the end? this is what i have so far and i can't figure out how to not have the spaces at the end.

def spaceitout(string,amount):
    amountint= int(amount)
    pile= ""
    for char in string:
        pile= pile + char + " "*amount
    print pile 

Use .strip() at the end. .strip() removes leading and trailing whitespace from a string. You can read more about it in the docs .

def spaceitout(string,amount):
    amountint= int(amount)
    pile= ""
    for char in string:
        pile= pile + char + " "*amount
    return pile.strip()

Python strings have a built-in method that does this for you far more efficiently than any explicit loop:

def spaceitout(string,amount):
    amount = int(amount)
    print (" " * amount).join(string)

That multiplies the space to create the joiner string, then calls .join on it with the string as an argument; since str s are iterables of their own characters, this will insert the spaces between every letter without ever adding them to the end of the result. If the string itself might contain trailing whitespace, then you might still need to strip , but the join avoids adding any in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM