1

I have a list of strings with the same pattern and I want to extract the middle of those strings

my_list=["This is my first string","This is my second string"]
my_list2=[string[5:] for string in my_list]
my_list2=[string[:-7] for string in my_list]

Output: ["is my first","is my second"] My solution is working but How can I simplify the two list comprehensions into one line of code ?

2 Answers 2

5

Whenever you use a list comprehension, it generates a new list, therefore, your last saved value in my_list2 was overwritten. There is no reason to use 2 list comprehensions then:

In [1]: my_list=["This is my first string","This is my second string"]
In [2]: [string[5:-7] for string in my_list]
Out[2]: ['is my first', 'is my second']
Sign up to request clarification or add additional context in comments.

Comments

-1

As far I understand your problem you are just removing first and last word So, for this use split and exclude first and last words

Comments

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.