wizton
wizton

Reputation: 17

Python - How can I separate characters and integers from a string into sub-strings?

I am writing a program that allows the user to create expedition kit lists. The last area I need to configure is multiplying the amounts of equipment (from a saved expedition) per person by how many people are on the expedition, to give the user how much of that piece of equipment they will need.

However, the problem is, when the user enters how much of a certain equipment they would like, the unit goes with the amount. For example, in the file, it looks like this: Water 100ml

So, I need to multiply the "100" by a number, but need to separate it from "ml" first. I have no code necessary to show, as I don't have any idea where to start.

Note: I am using python 3.2, I can easily change some syntax, but any extra effort to change it would be great, but don't bother too much :)

Upvotes: 0

Views: 184

Answers (2)

anon582847382
anon582847382

Reputation: 20361

You can extract the values using re.match:

>>> import re
>>> item = "Water\n100ml\n"
>>> re.match(r"([0-9]+)([a-z]+)", item.split()[1], re.I).groups()
('100', 'ml')

And then do whatever you need to do with them.


EDIT: For your second point in your comment, if you have a file in specified format you could do:

with open('file.txt') as f:
    data = f.readlines()
    items = list(zip(data[0::2], data[1::2]))  # A list of items like ('Water', '100ml')

And then you could use the previous regex for each item in that list, except with some_item[1] as the string to be searched; where some_item is the current value during for example an iteration.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

Use re.sub for this:

>>> import re
>>> s = "Water 100ml"
>>> re.sub(r'\d+', lambda m: str(int(m.group())*5), s)
'Water 500ml'

Upvotes: 2

Related Questions