1

I have multiple string variables that store some text data. I want to perform the same set of tasks on all strings. How can I achieve this in Python?

string_1 = "this is string 1"
string_2 = "this is string 2"
string_3 = "this is string 3"

for words in string_1:
    return the second word 

Above is just an example. I want to extract the second word in every string. Can I do something like:

for words in [string_1, string_2, string_3]:
    return the second word in each string

2 Answers 2

3

You can use a list comprehension to chain up the second word in those strings. split() breaks your sentence down into word components by consuming spaces.

lines = [string1, string2, string3]

>>>lines[0].split()
['this', 'is', 'string', '1']

>>>[line.split()[1] if len(line.split()) > 1 else None for line in lines]
['is', 'is', 'is']

Edit Added conditional checks to prevent indexing failures

Sign up to request clarification or add additional context in comments.

2 Comments

better use line.split() so if there are multiple spaces it still works. Also, the issue with listcomp is that if the sentence has only 1 word, it crashes when accessing the second element.
@Jean-FrançoisFabre Switched to using split without the character argument per your suggestion and added a conditional statement to prevent indexing errors. Thanks for pointing out!
1

Yes you could do

for sentence in [string_1, string_2, string_3]:
   print(sentence.split(' ')[1]) # Get second word and do something with it

This will work assuming that you have minimum of two words in the string and each separated by a space.

2 Comments

The return statement exits after the first iteration. This doesn't work.
Yeah it is. Sorry for that. Made the change now

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.