[英]How to print a variable which is created using for loops
I am trying to automate some of the manual tasks using python3 and I am not sure how to print a variable.我正在尝试使用 python3 自动执行一些手动任务,但我不确定如何打印变量。 I know I can use print(f"https://{ip1}", but I am trying to solve this problem using "for loops"我知道我可以使用 print(f"https://{ip1}", 但我正在尝试使用“for 循环”来解决这个问题
Here is the part of the code.这是代码的一部分。
......
def hostFile():
hostConf = (projdateprojname[9:])
print("\n\tEnter legacy host IP")
ip1 = input(prompt)
print("\n\tEnter legacy guest IP")
ip2 = input(prompt)
print("\n\tEnter legacy host IP")
ip3 = input(prompt)
print("\n\tEnter legacy guest IP")
ip4 = input(prompt)
print(f"\n[{hostConf}-1]")
print(f"{ip1}")
print(f"{ip2}")
print(f"{ip3}")
print(f"{ip4}")
for i in range(1, 5):
listofurl = ("ip" + str(i))
print(f"https://{listofurl}")
Script output for the last part:
https://ip1
https://ip2
https://ip3
https://ip4
I am expecting to see, for example
https://10.1.1.199
https://10.1.1.200
https://10.1.1.201
https://10.1.1.202
I see what you were trying to do, just one adjustment change我明白你想做什么,只是一个调整变化
listofurl = ("ip" + str(i))
to到
listofurl = (locals()["ip" + str(i)])
locals()
return a dictionary {}
of variables in the current scope, ["ip" + str(i)]
gets translated to ["ip<i>"]
where i
changes value during each phase of the loop locals()
返回当前 scope 中变量的字典{}
, ["ip" + str(i)]
被转换为["ip<i>"]
,其中i
在循环的每个阶段更改值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.