You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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])

修正逻辑说明

  1. greeting[1:]:去掉原字符串开头的小写"h",得到子串"ello how are you, what?"
  2. without_first_h.rfind('h'):定位该子串中最后一个"h"的位置(即"what"里的"h")
  3. without_first_h[:last_h_index]:截取到该"h"之前的部分,得到"ello how are you, w",从而排除了首尾的"h"
  4. target_str.title()[::-1]:将子串转为标题格式后反转,得到期望的输出结果

内容的提问来源于stack exchange,提问作者James Leroy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:11:30