Python字符串切片

时间:2011-05-27 07:22:49

标签: python string slice

如何将字符串与我的列表进行切片。

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

我希望代码删除“如何”并打印其余部分。

 dye my brunet hair to blonde?

有什么想法吗?

4 个答案:

答案 0 :(得分: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? 

当以这种方式使用时,replace将用第二个参数替换其第一个参数的所有出现。它还采用可选的第三个参数,这将限制所做的替换次数。例如,如果您只想替换第一次出现的“如何”,那么这很有用。

答案 1 :(得分:3)

这应该确保只在开始时进行更换。但是效率不是很高。如果很清楚你想做什么,可能会有所帮助。

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 :(得分:2)

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

答案 3 :(得分:1)

由于其他答案没有考虑到列表:

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