简体   繁体   中英

Split string after certain character

I have this line of code in my python file:

included_users = os.environ["INCLUDED_USERS"]

where in one of my config files I have:

INCLUDED_USERS = fname.lname:UDWADAW,fname2.lname2:DADWAD,fname3.lname3:DWAFUD,etc.

How can I make it so that I filter the INCLUDED_USERS list to append to an array with just the strings after ":" ?

so for example I want from the INCLUDED_USERS list:

INCLUDED_USERS_ID = ["UDWADAW,DADWAD,DWAFUD"]

Split on commas to get a list of name:value pairs, then split each pair on a colon.

for pair in included_users.split(","):
    value = pair.split(":")[1]
    INCLUDED_USERS_ID.append(value)

Simple list comprehension, but you need to convert included_user to string.

INCLUDED_USERS = "fname.lname:UDWADAW,fname2.lname2:DADWAD,fname3.lname3:DWAFUD"
INCLUDED_USERS_ID = [ i.split(':')[1]   for i in INCLUDED_USERS.split(',')]
print(INCLUDED_USERS_ID)

Output of the above code is

['UDWADAW', 'DADWAD', 'DWAFUD']

Hope this helps your case, if not please feel free to comment. Thansks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM