1

How can i slice a string comparing with my list.

string = "how to dye my brunet hair to blonde? "
list = ['how', 'how to',...]

I want the code to remove "how to" and print the rest.

 dye my brunet hair to blonde?

Any idea?

1
  • BTW, it's a good habit to avoid giving your variables the same names as important builtins unless you really want that behaviour (sometimes you do!) IOW, you probably don't want to call your lists "list". Commented May 27, 2011 at 8:00

4 Answers 4

6
In [1]: s = "how to dye my brunet hair to blonde? "

In [2]: print s.replace("how to", "")
 dye my brunet hair to blonde? 

When used this way, replace will replace all occurrences of its first argument with the second argument. It also takes an optional third argument, which would limit the number of replacements made. This is useful if, for example, you only wish to replace the first occurrence of "how to".

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

1 Comment

"how to figure out how to change a lightbulb?"
3

This should make sure the replacement is only done in the beginning. Not terribly efficient, though. It might help if it was clear what you wanted done.

string = "how to dye my brunet hair to blonde? "
list = ['how', 'how to',"bananas"]
list.sort(key=len,reverse=True)  # sort by decreasing length

for sample in string, "bananas taste swell", "how do you do?":
  for beginning in list:
    if sample.startswith(beginning):
      print sample[len(beginning):]
      break
  else:   # None of the beginnings matched
    print sample

2 Comments

+1 for doing the reverse sort to handle the ordering dependency
+1, and @bekman: please remember to mark this as “the” answer to your question.
2
>>> string[len('how to'):]
' dye my brunet hair to blonde? '

Comments

1

Since the other answers don't take the list into account:

input = "how to be the best python programmer of all time"
#note that the longer ones come first so that "how" doesn't get cut and then "how to" never exists
stopwords = ['how to', 'how']
for word in stopwords:
    input = input.replace(word, '', 1)

print input

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.