John
John

Reputation: 3070

Split from text in python

I have a text likes

input = ID-name-birth

I want to extract the ID, name and birth separately. So I used

ID= input.split('-')[0]
name= input.split('-')[1]
birth = input.split('-')[2]

It worked. But sometimes, my customer insert likes

input = ID_name_birth

So I need to change the code to

ID= input.split('_')[0]
name= input.split('_')[1]
birth = input.split('_')[2]

I want to make my code work any situation wherever insert '_' nor '-'. Do we have an option to deal with the problem?

Upvotes: 0

Views: 46

Answers (1)

DeepSpace
DeepSpace

Reputation: 81594

Use re.split, and you also do not need to call it 3 times, use unpacking:

import re

for input_str in 'id-name-birth', 'id_name_birth':
    ID, name, birth = re.split('[-_]', input_str)
    print(ID, name, birth)

Outputs

id name birth
id name birth

Upvotes: 1

Related Questions