简体   繁体   中英

Check if a string is a ordered sublist of a list

Let's say that I have a list with the following pattern:

lst=['A','B','C','D']

and I have the three following strings

str1='BCD'
str2='ABD'
str3='CD'

As you can see, str1 and str3 are both ordered substrings of the pattern in lst, while str2 isn't. I need to find a way to check whether this is true or not.

Can this be done? Should lst be something like ['ABCD'] instead of ['A','B','C','D'] for it to work?

You can simply join the list to a string with

lstAsString = ''.join(lst)

and then check for a string if it's a part of this with the in operator

if str2 in lstAsString:
   print("This is an ordered substring")

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