Remove everything that comes after a word that is after a specific word in Python

Question:

I have few strings like:

This is a beautiful string 1 - written by a dog
This is a beautiful string 2 written by a fly
This is a beautiful string 3 ewh

With python, I want to remove everything that comes after string X. After filtration I want the string to be:

This is a beautiful string 1
This is a beautiful string 2
This is a beautiful string 3

There can be anything after "string", it’s not necessary that it’ll be a number.

Is this possible?

I looked for ways of doing this and found .rsplit() but it didn’t work the way I expected.

Asked By: ippsec

||

Answers:

I guess simple regexp will do the job:

import re

p = re.compile("string d+")
for line in lines:
    if resp := p.search(line):
        print(line[0:resp.end()])
    else:
        print(line)
Answered By: Mike

Code you can try:

import re

s1 = "This is a beautiful string 1 - written by a dog"

my_regex = re.compile(r"(?P<final>This is a beautiful string)")

output_s1 = re.search(my_regex, s1)['final']
print(output_s1)

Output

"This is a beautiful string"
Answered By: Avad

Assuming this is your string

 x = """This is a beautiful string 1 - written by a dog
    This is a beautiful string 2 written by a fly
    This is a beautiful string 3 ewh""" 

For single line:

print(x.replace((x[x.index("g")+3:]), ""))

output:

This is a beautiful string 1

For everyline:

print([y.replace((y[y.index("g")+3:]), "") for y in x.splitlines()])

output:

['This is a beautiful string 1', 'This is a beautiful string 2', 'This is a beautiful string 3']
Answered By: Alankrith G
x=This is a beautiful string 1 - written by a dog
y=This is a beautiful string 2 written by a fly
z=This is a beautiful string 3 ewh

list=[x,y,z]

string=[]
new_list=[]
for i in range (1,len(list)+1):
    sep='string {}'.format(i)
    string=list[i-1].split(sep,1)[0]+sep
    new_list.append(string)

new_list

Output

https://i.stack.imgur.com/FDP80.png

Answered By: Mohd Shadab

Use re.match or re.findall:

import re

string1 = 'This is a beautiful string 1 - written by a dog'
string2 = 'This is a beautiful string 2 written by a fly'
string3 = 'This is a beautiful string 3 ewh'
string4 = 'This is a beautiful string whatever by me'

res1 = re.match('(.*string w+)', string1)[0]
res2 = re.findall('(.*string w+)', string2)[0]
res3 = re.match('(.*string w+)', string3)[0]
res4 = re.findall('(.*string w+)', string4)[0]

print(res1), print(res2), print(res3), print(res4)

# This is a beautiful string 1
# This is a beautiful string 2
# This is a beautiful string 3
# This is a beautiful string whatever
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.