Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
Vicky Avatar asked Dec 18 '18 08:12

Vicky


People also ask

How do you split part of a string in Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.

How do you split a string into multiple strings in Python?

Split String in Python. To split a String in Python with a delimiter, use split() function. split() function splits the string into substrings and returns them as an array.

How do you split a string into 3 parts in Python?

Python 3 - String split() Method The split() method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.


2 Answers

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']
like image 118
Rakesh Avatar answered Oct 14 '22 21:10

Rakesh


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']
like image 22
Tim Biegeleisen Avatar answered Oct 14 '22 21:10

Tim Biegeleisen