简体   繁体   中英

Separation of a splited string

def getOnlyNames(unfilteredString):
    unfilteredString = unfilteredString[unfilteredString.index(":"):]
    NamesandNumbers = [item.strip() for item in unfilteredString.split(';')]
    OnlyNames = []

    for i in len(productsPrices):
        x = [item.strip() for item in productsPrices[i].split(',')]
        products.append(x[0])
    return products

So I'm trying to make a function that will separate a following string

 "Cars: Mazda 3,30000;     Mazda 5, 49900;"

So I will get only:

Mazda 3,Mazda 5

First I was removing the:

then I try to get only the name of the car without the price of it

You can use regex for this:

import re
>>> s = "Cars: Mazda 3,30000; Mazda 5, 49900;"
>>> re.findall("[:;]\W*([^:;]*?)(?:,)", s)
['Mazda 3', 'Mazda 5']
>>> s = "Mazda 3, 35000; Cars: Mazda 4,30000;     Mazda 5, 49900;"
>>> re.findall("[:;]\W*([^:;]*?)(?:,)", s)
['Mazda 4', 'Mazda 5']
"Cars: Mazda 3,30000;     Mazda 5, 49900;" 
  • split on the colon
    • ['Cars', ' Mazda 3,30000; Mazda 5, 49900;']
  • split the last item on the semicolon
    • [' Mazda 3,30000', ' Mazda 5, 49900', '']
  • split the first two items on the comma.
    •  [' Mazda 3', '30000'], [' Mazda 5', ' 49900']
  • take the first item of each and strip the whitespace
    • 'Mazda 3'
    •  'Mazda 5'

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