简体   繁体   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?

I am trying to store the data of a variable of a function in a variable in my main program.我试图将函数变量的数据存储在主程序的变量中。 The goal of this program is to ask for an input(Authors name) and add spaces if the length of the value satisfies the condition of it being less than a value, in this case whatever is stored in numb(16).该程序的目标是要求输入(作者姓名)并在值的长度满足小于值的条件时添加空格,在这种情况下,无论存储在 numb(16) 中。

My function code is this:我的功能代码是这样的:

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

I'm using it for this:我正在使用它:

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

The output of the function would be "Author.........." but for the program It's "Author".该函数的输出将是“作者.......”但对于程序它是“作者”。 How can I get auth to be stored in Author?如何获得存储在 Author 中的授权? Thank you.谢谢你。

You should return the value from the function instead of printing it.您应该从函数返回值而不是打印它。 Also, your function is implemented very inefficiently.此外,您的功能执行效率非常低。 Use format strings instead of the loop:使用格式字符串而不是循环:

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

Do not call str() , input already returns a string.不要调用str()input已经返回一个字符串。 And do not capitalize variable names, this is against Python style guide:并且不要将变量名大写,这是违反 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