[英]Python: Is there a way to find and remove the first and last occurrence of a character in a string?
The problem: 问题:
Given a string in which the letter h occurs at least twice. 给定一个字符串,其中字母h至少出现两次。 Remove from that string the first and the last occurrence of the letter h, as well as all the characters between them.
从该字符串中删除字母h的第一个和最后一个出现以及它们之间的所有字符。
How do I find the first and last occurrence of h? 如何找到h的第一个和最后一个出现? And how can I remove them and the characters in between them?
以及如何删除它们以及它们之间的字符?
#initialize the index of the input string
index_count =0
#create a list to have indexes of 'h's
h_indexes = []
#accept input strings
origin_s = input("input:")
#search 'h' and save the index of each 'h' (and save indexes of searched 'h's into h_indexes
for i in origin_s:
first_h_index =
last_h_index =
#print the output string
print("Output:"+origin_s[ : ]+origin_s[ :])
You need to use regex: 您需要使用正则表达式:
>>> import re
>>> s = 'jusht exhamplhe'
>>> re.sub(r'h.+h', '', s)
'juse'
string = '1234-123456789'
char_list = []
for i in string:
char_list.append(string[i])
char_list.remove('character_to_remove')
According to the documentation, remove(arg)
is a method acting on a mutable iterable (for example list
) that removes the first instance of arg
in the iterable. 根据文档,
remove(arg)
是作用于可变可迭代对象(例如list
)的方法,该方法删除可迭代对象中arg
的第一个实例。
This will help you to understand more clearly: 这将帮助您更清楚地了解:
string = 'abchdef$ghi'
first=string.find('h')
last=string.rfind('h')
res=string[:first]+string[last+1:]
print(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.