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

Python获取字符串中间字符代码报错,请求技术协助

修复获取字符串中间字符的代码报错问题

你的代码跑不起来是因为字符串的索引必须是整数,但len(x_user_input)/2在Python里会返回浮点数——比如输入长度为4的字符串会得到2.0,长度为5的话是2.5,用浮点数当索引直接触发TypeError。另外user_input本身就是字符串,没必要再用str()转一遍。

下面给两个修复方案:

方案1:不管奇偶,返回单个中间字符(偶数长度取偏左的那个)

user_input = input("Enter a word: ")
length = len(user_input)
middle_index = length // 2  # 用整数除法得到整数索引
print(user_input[middle_index])

方案2:区分奇偶长度,偶数返回中间两个字符,奇数返回单个

user_input = input("Enter a word: ")
length = len(user_input)
middle_index = length // 2
if length % 2 == 1:
    print(user_input[middle_index])
else:
    # 截取中间两个字符
    print(user_input[middle_index-1:middle_index+1])

关键改动说明

  • 用//做整数除法,直接得到符合要求的整数索引
  • 删掉了多余的str(user_input)转换,input()返回的本来就是字符串
  • 方案2增加了奇偶判断,能更灵活处理不同长度的输入

内容的提问来源于stack exchange,提问作者Beatriz Mcknight

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:36:15