开发者

Python string slice

开发者 https://www.devze.com 2023-03-08 22:15 出处:网络
How can i slice a string comparing with my list. string = \"how to dye my brunet hair to blonde? \" list = [\'how\', \'how to\',...]

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 co开发者_StackOverflow社区de to remove "how to" and print the rest.

 dye my brunet hair to blonde?

Any idea?


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".


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


>>> string[len('how to'):]
' dye my brunet hair to blonde? '


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
0

精彩评论

暂无评论...
验证码 换一张
取 消