如何从用户输入的字符串中删除引号,并将其用于其他目的?

问题描述 投票:0回答:2
google = {
'Pixel 4' : 64000,
'Pixel 3' : 54000,
'Pixel 2' : 42000,
'Pixel' : 25000
}

iPhone = {
'11' : 95000,
'X' : 80000,
'7S' : 70000,
'7' : 42000
}
print("Mobile Brand = google, iphone")
print(f"{google} \n{iPhone}")
print("Please write the name of brand as mentioned in list")
m = input("Which mobile company do you like? ")  
'''Here, if user inputs google then it will be initiated as 'google' in the memory '''
n = str(input(f"Which model of {m} you want to buy? ")) # user inputs Pixel 4
m1 = m.replace("'", "") #Here I'm trying to make 'google' as google to use it for next variable
print(f"The price of {n} :", m1[n]) 
''' Here the value should be as google['Pixel 4'] and value should print 64000 but it gives type error because m1[n] is assumed as 'google'['Pixel 4']. Is there any way to initialized 'google''s to google only? '''
print(f"The price of {n} :", m1[n])

如果我使用print(f“ {n}的价格:”,google [n]),则该程序可以正常工作。

这是错误...TypeError:字符串索引必须是整数请帮助我!!

python python-3.x
2个回答
1
投票

您需要从所选的品牌词典中检索模型。

print(f"The price of {n} :", globals()[m1][n]) 

4
投票

这是一个很好的示例,为什么您应该使数据/信息远离名称。正确的方法是具有适当的数据结构。

brands = {'google':{
'Pixel 4' : 64000,
'Pixel 3' : 54000,
'Pixel 2' : 42000,
'Pixel' : 25000
},
'iphone':{
'11' : 95000,
'X' : 80000,
'7S' : 70000,
'7' : 42000
}}

brand = input(f"Which mobile company do you like: {','.join(brands.keys())}?").lower()  
model = (input(f"Which model you want to buy: {','.join(brands[brand].keys())}? "))
print(f"The price of {model} is {brands[brand][model]}")

输出

Which mobile company do you like: google,iphone?google
Which model you want to buy: Pixel 4,Pixel 3,Pixel 2,Pixel? Pixel
The price of Pixel is 25000

-1
投票

尝试使用int(m1 = m.strip('\"'))

© www.soinside.com 2019 - 2024. All rights reserved.