gpt4 book ai didi

python - 我在 Codewars 中遇到了这个错误,但它在 PyCharm 中工作正常吗?

转载 作者:行者123 更新时间:2023-12-04 08:09:49 24 4
gpt4 key购买 nike

这是我正在研究的问题!
拆分字符串
完成解决方案,以便将字符串拆分为两个字符对。如果字符串包含奇数个字符,那么它应该用下划线 ('_') 替换最后一对缺少的第二个字符。

def solution(s):
answer = []
a = 0
if (len(s) % 2) != 0:
a = s + "_"
for i in range(len(a) // 2):
answer.append(a[2 * i:2 * i + 2])
return answer

Traceback (most recent call last):
File "main.py", line 13, in <module>
test.assert_equals(solution(inp), exp)
File "/home/codewarrior/solution.py", line 6, in solution
for i in range(len(a) // 2):
TypeError: object of type 'int' has no len()

最佳答案

问题是您将 a 初始化为整数 a=0如果 s 是偶数,则行 a = s + "_"不被执行。所以a在这种情况下仍然是整数。
这就是为什么(len(a) // 2)给出一个错误。 len不适用于整数,仅适用于字符串。
要解决此问题,请初始化 a=s

关于python - 我在 Codewars 中遇到了这个错误,但它在 PyCharm 中工作正常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66038433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com