find_all
find_all

Reputation: 197

Test for single continuous string in list of strings

I have a list of strings that I want to encase in brackets, but only if two or more words exist in each value.

For example:

list = ['test', 'go test', 'test again', 'test2 ']

My first thought was to just test for a space, but it is not always the case that a single word value will not contain a space, as I purposefully included in the 'test2 ' value (notice the space at the end of the value).

I could just strip the whitespace at the beginning and end of the word, and then test for the space like:

list2 = []
for b in list:
    a = b.strip()
    list2.append(a)

Would give me an output with no space at the beginning or end of a word, which would then allow me to test for a space - but that is an additional step.

Is there any way I can test for a single continuous string without eliminating whitespace at the beginning and end of each word?

The desired output would look like:

list = ['test', '[go test]', '[test again]', 'test2 ']

Upvotes: 0

Views: 94

Answers (2)

Smart Manoj
Smart Manoj

Reputation: 5834

Not need to create a new list. While checking you can strip space.

mylist = ['test', 'go test', 'test again', 'test2 ']
print([f'[{i}]' if ' ' in i.strip() else i for i in mylist])
#['test', '[go test]', '[test again]', 'test2 ']

Upvotes: 0

Transhuman
Transhuman

Reputation: 3547

using the below

mylist = ['test', 'go test', 'test again', 'test2 ']
['[' + i + ']' if len(i.split())>1 else i for i in mylist]
#['test', '[go test]', '[test again]', 'test2 ']

Upvotes: 4

Related Questions