2016-11-17 40 views
1
text='I miss Wonderland #feeling sad @omg' 
prefix=('#','@') 
for line in text: 
    if line.startswith(prefix): 
     text=text.replace(line,'') 
print(text) 

输出应该是:去除startswith特定字符的Python字符串

'I miss Wonderland' 

但我的输出是原始字符串的前缀去掉

回答

1

这样看来,你不实际上是想删除整个“字符串”或“行”,而不是字?然后,你会想你的字符串分割成单词:

words = test.split(' ') 

现在,通过每个元素words迭代,第一个字母进行支票。你的情况

result = "" 
for word in words: 
    if !word.startswith(prefix): 
     result += (word + " ") 
0

for line in text会遍历文本中的每个字符,而不是每个字:最后,结合这些元素回一个字符串。因此,当它达到例如'#','#feeling'时,它将删除#,但'feeling'将保留,因为该字符串中的其他字符都不以'#''#'开头。您可以确认你的代码是由角色性格去这样做:

for line in text: 
    print(line) 

尝试,而不是下面的,它不以单行过滤:

text = 'I miss Wonderland #feeling sad @omg' 
prefix = ('#','@') 
words = text.split() # Split the text into a list of its individual words. 

# Join only those words that don't start with prefix 
print(' '.join([word for word in words if not word.startswith(prefix)]))