如何在python中用空格设置变量名

2024-04-25 22:13:45 发布

您现在位置:Python中文网/ 问答频道 /正文

代码有一个变量名,其空格等于变量值,如下所示:

PC 1  =  "192.168.10.1"

PC 2  = "192.168.20.1"

执行此获取时:

SyntaxError: invalid syntax

如何解决这个问题??

我没办法把变量名改成其他的。它将是PC 1(PC空间1),并为此分配ip地址。


Tags: 代码ip地址空间空格syntaxpc办法
2条回答

在带有空格的源代码中不能有变量名,但可以使用dict

computers = {}
computers['PC 1'] = 'some ip'
computers['PC 2'] = 'other ip'

对于Python,变量名中不可能有空格。

如果要将文件解析为配置文件或其他文件,请尝试以下操作:

ip.config:配置

PC 1 = "192.168.10.1"
PC 2 = "192.168.20.1"

ip.py公司

ip_config = {}
with open("ip.config") as f:
    for line in f:
        key, value = line.split("=")
        ip_config[key.strip()] = value.strip(" \"\n")

print ip_config["PC 1"]
print ip_config["PC 2"]

输出:

192.168.10.1
192.168.20.1

相关问题 更多 >