Home > Software engineering >  how to deliminate string with different and multiple deliminater
how to deliminate string with different and multiple deliminater

Time:10-18

I have a string (python), that has the date, model, make, and the year it is below:

string = "Mar 17 1997 H569, CAT: 2022"

I want to write a program that will ask the user to enter the string, and the program will automatically do something like:

date: data
model:data
make: data
year: data

The question, how can I deliminate,since I have space, comma, colon, etc. If I use characters then the problem will be not all makes and model have the same number of characters. What I am trying to do is to deliminate a string with more than once deliminater randomly mixed, in python?

Help will be apprecieted

CodePudding user response:

One option is to use a regex:

import re

regex = re.compile('(\w  \d  \d ) (\w ), (\w ): (\d )')

string = "Mar 17 1997 H569, CAT: 2022"
regex.findall(string)

output: [('Mar 17 1997', 'H569', 'CAT', '2022')]

CodePudding user response:

string = input('date :') #"Mar 17 1997 H569, CAT: 2022"
mounth,day,dyear,model,make,year=string.split()
print(f'date:{day}/{mounth}/{year}')
print(f'model:{model.strip(",")}')
print(f'make:{make.strip(":")}')
print(f'year:{year}')
  • Related