简体   繁体   English

在字符串中的每个字母之间添加空格,然后在末尾没有空格

[英]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() .strip() removes leading and trailing whitespace from a string. .strip()从字符串中删除前导和尾随空格。 You can read more about it in the docs . 您可以在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: Python字符串具有一个内置方法,该方法比任何显式循环为您高效得多:

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; 这将空间乘以创建连接符字符串,然后使用string作为参数在其上调用.join 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. 由于str是自己的字符可迭代,因此将在每个字母之间插入空格,而无需将其添加到结果的末尾。 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. 如果字符串本身可能包含结尾的空格,那么您可能仍然需要strip ,但是join避免首先添加任何空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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