0

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
3
  • What does string contain? Do you want to check all elements for presence of '[' ? Commented Nov 22, 2021 at 6:58
  • add the definition of string in the code Commented Nov 22, 2021 at 7:03
  • done, edited with the definition. Commented Nov 22, 2021 at 7:09

2 Answers 2

1

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)):
    .....
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Hohoo, that is pretty useful too, it's exactly the way I was trying to do with the right changes. In my code example I could do "any(element[0] == '[' for element in strings)". Thank you for your contribution Mark, appreciate it. Really learnt something new today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.