简体   繁体   中英

Python - String list check

I'm relatively new with Python, so I still struggle a bit with character manipulation.

I tried many variations of this piece of code:

print([for element in string if element[0] == '['])

"string" is a list of [tag] messages, which i splited considering '\n', so I'm trying to format it and merge separated elements of the same message. Right now I'm doing:

for count, element in enumerate(string):
        try:
            if element[0] != '[':
                string[count - 1] = string[count - 1] + ' ' + string[count]
                string.pop(count)
                count = count - 1

But it only works once per couple messages, so my goal is to check if all are properly merged.

My expected output is True if there is a "[" in the first character of the current element in the string list. So I can put it on a while loop:

while([for element in string if element[0] == '[']):
   # do something

You are returning a list with the comprehension list. Maybe this will work better for your case

def verify(s)
    for element in s:
        if element[0] == '[':
            return True
    return False

while(verify(s)):
    .....

A succinct way to do this is with any() . You can also use the build-in startswith() which helps the readability:

strings = ['hello', '[whoops]', 'test']
any(s.startswith('[') for s in strings)
# True

strings = ['hello', 'okay', 'test']
any(s.startswith('[') for s in strings)
# False

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