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
CodePudding user response:
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)):
.....
CodePudding user response:
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