简体   繁体   中英

Python string slice

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM