Extract only lines with two strings in the same line of text

Asked 2 years ago, Updated 2 years ago, 38 views

one two four four five
one two four
one four four five
one two ofive

Extract lines with only one and three strings from the text

one two four four five
one four four five

What should I do if I want to create the text?

python python3

2022-09-30 21:35

2 Answers

If the word order is one followed by three, you can extract it using the regular expression below.

import re
s="one two four five
one two four
one four four five
"""one two five""" 
s2 = '\n'.join(re.findall(r'^.*one.*three.*$', s, re.MULTILINE))
print(s2)


2022-09-30 21:35

If you want to use splitlines() to make a list of strings by line.

s="one two four four five
one two four
one four four five
"""one two five"""

For looping with a for statement, use the following code:

result='"
for line in s.splitlines (True):
    if 'one' in line and 'three' in line:
        result+=line

You can also use the expression to write as follows:

result='.join(x for x in s.splitlines(True) if 'one' in x and 'three' in x )

In addition, splitlines(True) lists newline characters, so you can process them without considering the model dependence of newline characters.


2022-09-30 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.