【问题标题】:Python: Is there a way to find and remove the first and last occurrence of a character in a string?Python:有没有办法找到并删除字符串中第一次和最后一次出现的字符?
【发布时间】:2019-10-18 06:51:24
【问题描述】:

问题:

给定一个字符串,其中字母 h 至少出现两次。 从该字符串中删除第一次和最后一次出现 字母 h,以及它们之间的所有字符。

如何找到 h 的第一次和最后一次出现?以及如何删除它们以及它们之间的字符?

#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[     :])

【问题讨论】:

标签: python string substring slice find-occurrences


【解决方案1】:

使用indexrindexslicing 的组合:

string = 'abc$def$ghi'
char = '$'
print(string[:string.index(char)] + string[string.rindex(char) + 1:])
# abcghi

【讨论】:

    【解决方案2】:

    你需要使用正则表达式:

    >>> import re
    >>> s = 'jusht exhamplhe'
    >>> re.sub(r'h.+h', '', s)
    'juse'
    

    【讨论】:

    • 好吧,你不需要。明确定位第一次和最后一次出现,然后对其余的进行切片也可以。
    【解决方案3】:

    如何找到 h 的第一次和最后一次出现?

    第一次出现:

    first_h_index=origin_s.find("h");

    最后出现:

    last_h_index=origin_s.rfind("h");

    我怎样才能删除它们以及它们之间的字符?

    Slicing

    【讨论】:

    • 我很高兴能帮上忙。请投票和/或接受此答案,以便其他人得到帮助。
    【解决方案4】:
    string = '1234-123456789'
    char_list = []
    for i in string:
        char_list.append(string[i])
    
    char_list.remove('character_to_remove')
    

    根据文档,remove(arg) 是一种作用于可变迭代(例如 list)的方法,它删除迭代中 arg 的第一个实例。

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    【解决方案5】:

    这将帮助您更清楚地理解:

    string = 'abchdef$ghi'
    
    first=string.find('h')
    
    last=string.rfind('h')
    
    res=string[:first]+string[last+1:]
    
    print(res)
    
    

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 2017-12-25
      • 2013-12-28
      • 2016-05-27
      • 1970-01-01
      相关资源
      最近更新 更多