簡體   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