String Python-将空字符串设置为0
我有字符串变量,例如其中两个是空的“” 这些空字符串应设置为0 然后,所有字符串变量都应该转换成整数,以便能够对其进行一些检查并返回它们 但我当前的问题是,我的循环没有将空字符串设置为0 我在运行脚本时获得以下输出:String Python-将空字符串设置为0,string,integer,String,Integer,我有字符串变量,例如其中两个是空的“” 这些空字符串应设置为0 然后,所有字符串变量都应该转换成整数,以便能够对其进行一些检查并返回它们 但我当前的问题是,我的循环没有将空字符串设置为0 我在运行脚本时获得以下输出: ['1000', '', '', '5'] Only Numbers! 你知道我如何处理循环后的变量吗? 不需要列表索引 def func(): bandwidth = 2000 voice = "1000" signal = &quo
['1000', '', '', '5']
Only Numbers!
你知道我如何处理循环后的变量吗?
不需要列表索引
def func():
bandwidth = 2000
voice = "1000"
signal = ""
stream = ""
business = "5"
empty_check = [voice, signal, stream, business]
for n in empty_check:
if n == "":
n = 0
print(empty_check) # check if "" was set to 0
try:
for n in empty_check:
n = int(n)
except ValueError:
print("Only Numbers!")
else:
if (empty_check[0] > 2000000) or (empty_check[0] > bandwidth):
print("Error")
elif (empty_check[1] > 1000000):
print("Error")
elif (empty_check[2] + empty_check[3]) > 95:
print("Error")
else:
return bandwidth, empty_check[0], empty_check[1], empty_check[2], empty_check[3]
test = func()
for循环仅将0分配给局部变量
n
,未修改列表。相反,您应该执行empty\u check[n]
来更改列表中索引处的值
我尝试在for循环中使用range
,以便将n
用作空\u检查列表中的索引,并成功获得以下输出:
['1000', 0, 0, '5']
以下是我使用的代码:
for n in range(len(empty_check)):
if empty_check[n] == "":
empty_check[n] = 0
print(empty_check) # check if "" was set to 0
try:
for n in range(len(empty_check)):
empty_check[n] = int(n)
它适用于0,谢谢,对于我必须做的整数:
try:for n in range(len(empty\u check)):empty\u check[n]=int(empty\u check[n])