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?
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.
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.
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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With