简体   繁体   中英

How to check for digit in list of string in python?

I have creates the following list:

list_article = ['My pasta $500.0', 'coffee $100.0', 'Oat can $50.0']

now I want to extract the numbers, make the sum and return a total like the following:

Total = 650.0

I have already created a function to add items to the list:

def add_item(item_name):
    item_qty = input('\nEnter amount to donate: ')
    item_qty_float = float(item_qty)
    item_str = f'{item_name} cost ${item_qty_float}'
    return item_str

user = ''
if user == '':
   print('You are not authorized.')
else:
    item_string = add_item(user)
    list_article.append(item_string)

Now I want to print out the total: Total = 650.0 Is there a way to extract the numbers inside the list of strings?

There is a way to extract the numbers, though it would be easier to just create a dictionary. Additionally, you could use a global variable outside the defined function so that every time you use your function, it adds their input to the global variable, thus adding up to your total. In case you aren't informed, a dictionary is like a list, but it has a key and value pair. For example:

dictionary = {'My pasta': 500.0, 'coffee': 100.0, 'Oat can': 50.0} <-- dictionary

The format for each dictionary entry separated by a comma is key: value . In order to access the value for a key in your dictionary, mention the variable and key inside brackets. Example:

dictionary = {'My pasta': 500.0, 'coffee': 100.0, 'Oat can': 50.0}
pasta_cost = dictionary['My pasta']

There are three methods you can use on dictionaries to extract data. "

dictionary.values() <-- Gives values in a list format
dictionary.items() <-- Gives both keys and values in a list format
dictionary.keys() <-- Gives keys in a list format

In your case, you might want to do something like this in order to add the values:

dictionary = {'My pasta': 500.0, 'coffee': 100.0, 'Oat can': 50.0}
total_cost = 0

for value in dictionary.values():
    total_cost += value
print(total_cost)

Which outputs: 650.0

If you truly want to extract the numbers from the strings, you could for each element in the list, use the .replace() method to take out anything that is alphabetical (or a space) and replace it with nothing.

Alternatively, you could use regex from the re module to find numbers in a string, but you would need to learn the syntax for regex.

Hope this helps!

In my opinion your data-structure is wrong.

But if task must have solving by your logic you can write

sum(float(s[s.rfind('$')+1:]) for s in list_article)

Try some regex, like this.

from re import findall
findall(r"[0-9]+\.[0-9]+", listItem)

https://regexr.com/6ifhn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM