Get substrings from a string by matching characters

I am trying to extract the prices from a string list that I have.

These is a sample of PriceList:

PriceList = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
             'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
             'Daily:$1,800.00\n\nWeekend:$2200.00',
             'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']

From the PriceList, I want to extract the MonthlyPrice and DailyPrice.

If MonthlyPrice is not present then it is NA.

I tried this code:

for item in PriceList:
    if item.find("Monthly")!= -1:
        MonthlyPrice = (item[8:])
    if item.find("Yearly")!= -1:
        YearlyPrice = (item[7:])
    if item.find("Weekly")!= -1:
        WeeklyPrice = (item[7:])

But it is not working, Kindly help me with this.

Expected Result

print(WeeklyPrice) for the 1st example on the list will give you $3600.00
print(DailyPrice) for the 1st example on the list will give you - NA.

Upvotes: 1

Views: 51

Answers (4)

martineau
martineau

Reputation: 123473

You could do it like this which first creates a temporary prices dictionary from each string of data in PriceList, and then uses the dictionary get() method to determine if specific values were in the string. Looking up things in dictionaries is very fast, so this implementation approach is also fairly efficient as well.

PriceList = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
             'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
             'Daily:$1,800.00\n\nWeekend:$2200.00',
             'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']

for data in PriceList:
    prices = dict(item.split(':') for item in data.split('\n\n'))
    MonthlyPrice = prices.get("Monthly", "NA")
    YearlyPrice = prices.get("Yearly", "NA")
    WeeklyPrice = prices.get("Weekly", "NA")
    print('MonthlyPrice: {:<10}, YearlyPrice: {:<10}, WeeklyPrice: {:<10}'.format(
            MonthlyPrice, YearlyPrice, WeeklyPrice))

Output:

MonthlyPrice: $15,120.00, YearlyPrice: NA        , WeeklyPrice: $3,600.00
MonthlyPrice: $33,600.00, YearlyPrice: NA        , WeeklyPrice: $8,400.00
MonthlyPrice: NA        , YearlyPrice: NA        , WeeklyPrice: NA
MonthlyPrice: $24,000.00, YearlyPrice: NA        , WeeklyPrice: $6,000.00

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Complete solution with regex.findall() function and specific regex pattern:

import re

price_list = ['Weekly:$3,600.00\n\nMonthly:$15,120.00',
              'Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00',
              'Daily:$1,800.00\n\nWeekend:$2200.00',
              'Day:$3,600.00\n\nWeekly:$6,000.00\n\nMonthly:$24,000.00']

base_dict = {'Yearly': 'NA', 'Monthly': 'NA', 'Weekly': 'NA', 'Daily': 'NA'}
pat = re.compile('(?:(Yearly|Monthly|Weekly|Daily):(\$[\d.,]+))')

for p_str in price_list:
    result_d = dict(base_dict)
    result_d.update(pat.findall(p_str))
    print('Yearly: {Yearly}, Monthly: {Monthly}, Weekly: {Weekly}, Daily: {Daily}'.format(**result_d))

The output:

Yearly: NA, Monthly: $15,120.00, Weekly: $3,600.00, Daily: NA
Yearly: NA, Monthly: $33,600.00, Weekly: $8,400.00, Daily: $3,000.00
Yearly: NA, Monthly: NA, Weekly: NA, Daily: $1,800.00
Yearly: NA, Monthly: $24,000.00, Weekly: $6,000.00, Daily: NA

Upvotes: 1

timgeb
timgeb

Reputation: 78690

Instead of awkwardly parsing that lonely string wrapped in a list, build a dictionary.

>>> prices = ['Daily:$3,000.00\n\nWeekly:$8,400.00\n\nMonthly:$33,600.00']
>>> prices = dict(time_price.split(':') for time_price in prices[0].split())
>>> prices
{'Monthly': '$33,600.00', 'Daily': '$3,000.00', 'Weekly': '$8,400.00'}

From here it's child's play to extract whatever you want.

>>> prices['Daily']
'$3,000.00'
>>> prices.get('NotFound', 'NA')
'NA'

Note that if you plan to do any arithmetic with the prices in the future converting them to float values is a good idea.

>>> prices = {k:float(v[1:].replace(',', '')) for k,v in prices.items()}
>>> prices
{'Monthly': 33600.0, 'Daily': 3000.0, 'Weekly': 8400.0}

Upvotes: 2

goodvibration
goodvibration

Reputation: 6206

Try this:

for item in PriceList:
    for line in item.splitlines():
        if line.startswith('Daily:'):
            DailyPrice = line[len('Daily:'):]
        if line.startswith('Weekly:'):
            WeeklyPrice = line[len('Weekly:'):]
        if line.startswith('Monthly:'):
            MonthlyPrice = line[len('Monthly:'):]

Upvotes: 1

Related Questions