按位置从字符串中删除单词,例如删除第二个字

时间:2018-11-04 11:35:50

标签: python string python-3.x

string = 'Hello how can i help'

是否有一种可能的方法可以删除字符串的第二个单词而无需确切说明该单词是什么。

3 个答案:

答案 0 :(得分:1)

string = 'Hello how can i help'
words = string.split()
#Use del command to remove element at nth position
del words[1]
mod_string = ' '.join(words)
print(mod_string)

答案 1 :(得分:0)

字符串是不可变的,但是您可以将列表理解与enumerate结合使用来创建新的字符串,而忽略按索引的特定单词。

string = 'Hello how can i help'

res = ' '.join([word for idx, word in enumerate(string.split()) if idx != 1])

print(res)

Hello can i help

请注意,索引从0开始,因此第二个单词的索引为1。按照@JonClements的注释,在这种情况下无需拆分每个单词,您可以限制通过将参数传递到str.split来拆分:

n = 1
res = ' '.join([word for idx, word in enumerate(string.split(None, n+1)) if idx != n])

最后,您可以通过提供要忽略的索引列表来概括该解决方案:

n = {1, 2}  # remove second and third words, use set for O(1) lookup
res = ' '.join([w for idx, w in enumerate(string.split(None, max(n)+1)) if idx not in n])

答案 2 :(得分:0)

string = 'Hello how can i help'    
new_list=string.split()    
second_word=new_list[1] # Get the second word!    
new_list.remove(second_word)    
print(" ".join(new_list)) # Convert the list to a string again