2

Possible Duplicate:
Delete Chars in Python

I want to know how to delete strings after a keyword in python

I will get lines in a txt file

What method could I use to do this.

For example:

"I have a book to read."

I want to delete all words after "book".

0

5 Answers 5

5

To remove everything after the first "book" including "book" itself:

s = "I have a book to read."
print(s.partition("book")[0])

To preserve the word "book":

print(''.join(s.partition("book")[:2]))

Both work whether "book" present in the string or not.

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

1 Comment

keyword should be included in the result string.
1

Yet another way to do this is with re.sub. (Output is shown interleaved with code.)

txt = 'I have a book to read'; key='book'
str = re.sub(key+'.*', key, txt)
str
'I have a book'
txt = 'I have a look to read'; key='book'
str = re.sub(key+'.*', key, txt)
str
'I have a look to read'

Comments

1

There are several ways to do this:

mystr = "I have a book to read." keyword = 'book'

Method 1:

def foo(mystr, keyword):
    try:
        i = mystr.index(keyword)
        return mystr[:i+len(keyword)]
    except ValueError:
        return mystr

Method 2:

def foo(mystr, keyword):
    i = mystr.find(keyword)
    if i >= 0:
        return mystr[:i+len(keyword)]
    else:
        return mystr

Method 3:

def foo(mystr, keyword):
    return ''.join(mystr.partition(keyword)[:2])

7 Comments

keyword should be included in the result string.
@MuMind: you're right. My solutions have been edited
If keyword is a variable, you might also want to use len(keyword) instead of 4
gah! you're right. I guess I'm just tired from my day
|
0

Use the stirng method find() which return the index of the first letter of the world:

str = "i have a book to read"
print str[:str.find("book") + len("book")]

This will work only because "book" exists in the string "i have a book to read". If this were not the case, this solution would not work as expected

1 Comment

wouldn't work if 'book' is not in the string. In that case, find returns -1 and you end up returning the first 3 characters of the input string
0

Regex would be good for this:

import re
m = re.match('(.*book)', line)
if m:
    line = m.group(1)

or

line = re.sub('book.*', 'book', line)

1 Comment

Um... guess somebody just really hates regexes? Or likes downvoting...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.