如何修改Python代码实现排除首尾h且保留内部h的字符串反转输出
问题解决:排除首尾字母"h"并反转字符串
现有代码
#This is my string known as "greeting". greeting = "hello how are you, what?" #This prints the greeting the normal way. print(greeting.title()) #This prints the greeting backwards and excluding the chosen letter "h" on the outside. print (greeting.title()[:greeting.find("h"):-1] + greeting[greeting.rfind("h")-1:5])
需求
输出问候字符串时排除首尾的字母"h"(保留内部的"h"),期望输出:
"Hello How Are You, What?" "W ,uoY erA woH olle"
当前代码输出
"Hello How Are You, What?" "?tahW ,uoY erA woH olle"
修正方案
原代码的切片逻辑错误,导致反转时包含了末尾的?tah部分。我们需要精准截取排除首尾"h"后的子串,再进行反转处理。
修正后的完整代码
# This is my string known as "greeting". greeting = "hello how are you, what?" # This prints the greeting the normal way. print(greeting.title()) # This prints the greeting backwards and excluding the chosen letter "h" on the outside. # 去掉开头的h,再移除最后一个h及之后的内容,转标题后反转 without_first_h = greeting[1:] last_h_index = without_first_h.rfind('h') target_str = without_first_h[:last_h_index] print(target_str.title()[::-1])
修正逻辑说明
greeting[1:]:去掉原字符串开头的小写"h",得到子串"ello how are you, what?"without_first_h.rfind('h'):定位该子串中最后一个"h"的位置(即"what"里的"h")without_first_h[:last_h_index]:截取到该"h"之前的部分,得到"ello how are you, w",从而排除了首尾的"h"target_str.title()[::-1]:将子串转为标题格式后反转,得到期望的输出结果
内容的提问来源于stack exchange,提问作者James Leroy
相关产品推荐
相关产品推荐

