Vicky
Vicky

Reputation: 829

How to split each individual value between two string in Python

variable=";CREATEDBY~string~1~~72~0~0~0~~~0;CREATEDBYNAME~string~1~~800~0~0~0~~~1;CREATEDBYYOMINAME~string~1~~800~0~0~0~~~2;CREATEDON~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~3;CREATEDONUTC~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~4"

How can I split each value which is between (; and ~)?

The result will be like CREATEDBY,CREATEDBYNAME,CREATEDBYYOMINAME,...

I have tried the below, but it's giving the first occurrence.

variable[variable.find(";")+1:myString.find("~")]

How do I get the list of strings by using the split?

Upvotes: 14

Views: 1552

Answers (5)

Raffi
Raffi

Reputation: 1920

import re

variable = ";CREATEDBY~string~1~~72~0~0~0~~~0;CREATEDBYNAME~string~1~~800~0~0~0~~~1;CREATEDBYYOMINAME~string~1~~800~0~0~0~~~2;CREATEDON~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~3;CREATEDONUTC~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~4"
pattern = re.compile (";(.+?)~")
matches = re.findall ( pattern, variable )
print matches

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521178

We can try using re.findall with the pattern ;(\w+)(?=~):

variable = ";CREATEDBY~string~1~~72~0~0~0~~~0;CREATEDBYNAME~string~1~~800~0~0~0~~~1;CREATEDBYYOMINAME~string~1~~800~0~0~0~~~2;CREATEDON~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~3;CREATEDONUTC~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~4"
result = re.findall(r';(\w+)~', variable)
print(result)

['CREATEDBY', 'CREATEDBYNAME', 'CREATEDBYYOMINAME', 'CREATEDON', 'CREATEDONUTC']

Upvotes: 14

Martin Frodl
Martin Frodl

Reputation: 657

Use regular expression with lookahead and lookbehind:

>>> import re
>>> re.findall(r'(?<=;).*?(?=~)', variable)
['CREATEDBY', 'CREATEDBYNAME', 'CREATEDBYYOMINAME', 'CREATEDON', 'CREATEDONUTC']

Upvotes: 5

fixatd
fixatd

Reputation: 1404

You can split() the string and then find() the first ~ for each one:

variable=";CREATEDBY~string~1~~72~0~0~0~~~0;CREATEDBYNAME~string~1~~800~0~0~0~~~1;CREATEDBYYOMINAME~string~1~~800~0~0~0~~~2;CREATEDON~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~3;CREATEDONUTC~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~4"
result = [item[:item.find('~')]  for item in  variable.split(';')]

print(result)

Upvotes: 5

Rakesh
Rakesh

Reputation: 82765

Using str.split

Ex:

variable=";CREATEDBY~string~1~~72~0~0~0~~~0;CREATEDBYNAME~string~1~~800~0~0~0~~~1;CREATEDBYYOMINAME~string~1~~800~0~0~0~~~2;CREATEDON~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~3;CREATEDONUTC~date~1~yyyy-MM-dd HH:mm:ss.SSS~26~0~0~0~~~4"

for i in variable.strip(";").split(";"):
    print(i.split("~", 1)[0])
#or
print([i.split("~", 1)[0] for i in variable.strip(";").split(";")])

Output:

CREATEDBY
CREATEDBYNAME
CREATEDBYYOMINAME
CREATEDON
CREATEDONUTC

['CREATEDBY', 'CREATEDBYNAME', 'CREATEDBYYOMINAME', 'CREATEDON', 'CREATEDONUTC']

Upvotes: 21

Related Questions