簡體   English   中英

如何從我制作的存儲在主程序中的全局變量中的函數中獲取字符串?

[英]How can I get a string from a function I made to be stored in a global variable I have in my main program?

我試圖將函數變量的數據存儲在主程序的變量中。 該程序的目標是要求輸入(作者姓名)並在值的長度滿足小於值的條件時添加空格,在這種情況下,無論存儲在 numb(16) 中。

我的功能代碼是這樣的:

def AddSpaces(auth,numb):
    print("Runs")
    while len(auth) < numb:
        auth = auth + " "
    print(auth)

我正在使用它:

Author = str(input("Author: "))
AddSpaces(Author,16)
print(Author)

該函數的輸出將是“作者.......”但對於程序它是“作者”。 如何獲得存儲在 Author 中的授權? 謝謝你。

您應該從函數返回值而不是打印它。 此外,您的功能執行效率非常低。 使用格式字符串而不是循環:

def add_spaces(auth, numb):
    return f"{auth:{numb}s}"

不要調用str()input已經返回一個字符串。 並且不要將變量名大寫,這是違反 Python 風格指南的:

author = input("Author: ")
author_with_spaces = add_spaces(author, 16)
print(author_with_spaces)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM