繁体   English   中英

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

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

我将如何创建一个程序,在其中可以在字符串的每个字母之间添加空格,然后在末尾没有空格? 这是我到目前为止所拥有的,我不知道如何在结尾处不留空格。

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

最后使用.strip() .strip()从字符串中删除前导和尾随空格。 您可以在docs中阅读有关它的更多信息。

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

Python字符串具有一个内置方法,该方法比任何显式循环为您高效得多:

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

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

暂无
暂无

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

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