Python 将包含字母和数字的字符串转换为浮点数(列表中的价格也包含其他内容)
我的代码有一个问题,我想做的是将列表中的字符串转换成浮点,这样我就可以用这些数字做数学运算。(这是在Python 3中)。比如说,Python 将包含字母和数字的字符串转换为浮点数(列表中的价格也包含其他内容),python,string,integer,int,Python,String,Integer,Int,我的代码有一个问题,我想做的是将列表中的字符串转换成浮点,这样我就可以用这些数字做数学运算。(这是在Python 3中)。比如说, price = float(line[i+1]) i+1为: Price: £139.99 我希望我的结果是 price = 139.99 谢谢 编辑:价格:139.99就是一个例子,有时也会出现其他价格,如价格:54.99 编辑:列表为 GTIN-8 Code: 12345670 Product name: Razer Blackwidow Chroma P
price = float(line[i+1])
i+1为:
Price: £139.99
我希望我的结果是
price = 139.99
谢谢
编辑:价格:139.99就是一个例子,有时也会出现其他价格,如价格:54.99
编辑:列表为
GTIN-8 Code: 12345670
Product name: Razer Blackwidow Chroma
Product price: £139.99
Product amount: 1
GTIN-8 Code: 44444440
Product name: Razer Deathadder Chroma
Product price: £54.99
Product amount: 1
GTIN-8 Code: 66666660
Product name: Paper
Product price: £0.99
Product amount: 100
GTIN-8 Code: 77777770
Product name: Steelseries QCK+ Heavy Mousepad
Product price: £19.99
Product amount: 1
因此,根据上面的列表,如果有人输入12345670,它将下降到价格线的两行,这一行我想去掉除数字以外的所有内容,这样我可以在每次有人输入产品时将它们添加到总价中
编辑:函数,由于粘贴问题而未正确缩进
def barcode()
choice = input("GTIN-8 ")
quantity = input("How many? ")
f = open("Items.txt", 'r')
lines = f.readlines()
for i in range(0,len(lines)):
line = lines[i]
if choice in (line):
f = open("Result.txt", 'a')
f.write(lines[i+1])
f.write(lines[i+2])
f.write("Num: " + quantity + "\n")
f.write("\n")
text = (lines[i+2])
price = float(line.split("£")[1])
amount = (quantity * price)
total += (amount)
anything_else = input("Any more?")
if anything_else == 'y':
f.close()
barcode()
else:
f.close()
what_to_do()
break
您可以在
处拆分字符串,并将第二个子字符串转换为浮点
例如:
line = "Price: £5000.8"
price = float(line.split("£")[1]) # in your case line => line[i+1]
希望这有帮助
编辑:
问题编辑后更改。
你可以试试这个:
def barcode():
print("\n" + "Amazon")
choice = input("GTIN-8 ")
quantity = input("How many? ")
f = open("Items.txt", 'r')
lines = f.readlines()
for i in range(0, len(lines)):
line = lines[i]
if choice in (line):
f = open("Result.txt", 'a')
f.write(lines[i + 1])
f.write(lines[i + 2])
f.write("Num: " + quantity + "\n")
f.write("\n")
text = (lines[i + 2])
price = float(text.split("£")[1]) # changed here
amount = (quantity * price)
total += (amount)
anything_else = input("Any more?")
if anything_else == 'y':
f.close()
barcode()
else:
f.close()
what_to_do()
break
text=“Price:£139.99”
所以Price=float(text[8:])
我做了一些研究,尝试了转换为float的一般方法,但都不起作用。我是新来的python@furas让我们使用float
而不是int
。理想情况下,他应该使用decimal.decimal@AyushShanker对,它必须是float:)请阅读编辑,我没有解释正确的错误:列表索引超出范围你能给我一些行列表中字符串的确切示例吗。例如:行[0]=“价格:88.99英镑”
行[1]=“价格:100.99英镑”
。。。so onGTIN-8代码:12345670产品名称:Razer Blackwidow Chroma产品价格:139.99英镑产品金额:1GTIN-8代码:4444444 0产品名称:Razer Deathadder Chroma产品价格:54.99英镑产品金额:1GTIN-8代码:666666666 0产品名称:纸张产品价格:0.99英镑产品金额:100GTIN-8代码:7777777 0产品名称:Steelseries QCK+Heavy鼠标垫产品价格:19.99英镑产品金额:1每次按enter键时,我都无法拆分它。您是否将所有产品价格都放在单独的列表或变量中。您的问题是将“价格:99.00英镑”转换为不同的金额。如果您没有单独的列表或变量中的价格,您应该将问题更改为也包含该价格。如果您有单独的价格字符串,请告诉我列表内容,如行[0]=“'price:$99.00”
等。