HelloAlll - 1 year ago 64
Python Question

# Convert a string with letters and numbers to a float (price in list with other things too)

I am having an issue with my code what I would like to do is convert a string from a list into a float so I can do maths with those numbers. (This is in Python 3). For example,

``````price = float(line[i+1])
``````

With i+1 being:

``````Price: £139.99
``````

What I want my result to be is,

``````price = 139.99
``````

Thanks!

EDIT: Price: 139.99 is an example, its sometimes other ones such as Price: 54.99

EDIT: List is

``````GTIN-8 Code: 12345670
Product name: Razer Blackwidow Chroma
Product price: £139.99
Product amount: 1
GTIN-8 Code: 44444440
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
``````

So with the list above if someone put in 12345670, it would go down two lines to the price line, with that line I want to take everything away but the numbers so I can add them to the total price each time someone enters a product.

EDIT: The function, not properly indented because paste problems.

``````def barcode():
print("\n" + "Amazon")
choice = input("GTIN-8 ")
quantity = input("How many? ")
f = open("Items.txt", 'r')
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
``````

You could split the string at `£` and convert the second substring to a float

For example:

``````line = "Price: £5000.8"
price = float(line.split("£")[1]) # in your case line => line[i+1]
``````

Hope this helps!

EDIT:

Changed after question edit. You could try this:

``````def barcode():
print("\n" + "Amazon")
choice = input("GTIN-8 ")
quantity = input("How many? ")
f = open("Items.txt", 'r')
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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download