python - Python中的反向单词功能问题
问题描述
我的代码几乎可以完美运行,除了第一个单词反转总是“错过”最后一个字符之外,句子的其余部分都可以正常工作。谁能找到调试此代码逻辑的错误?
def reverseWords(str):
str_len = len(str)
str = str[str_len-1::-1]
str_end = ''
stop = 0
index = 0
for i in range(str_len):
if (str[i] == ' '):
index = i - 1
str_end += str[index:stop:-1] + ' '
stop = i
elif (i == str_len-1):
index = i
str_end += str[index:stop - 1:-1]
return str_end
print(reverseWords("The greatest victory is that which requires no battle"))
output: battl no requires which that is victory greatest The
解决方案
在 Python 中执行此类操作的一种更惯用的方法是拆分、反转和连接:
def reverse_words(text):
words = text.split(' ')
reversed_words = []
for word in words:
reversed_words.append(word[::-1])
reversed_text = ' '.join(text)
return reversed_text
或者,在一个表达式中,
def reverse_words(text):
return ' '.join(w[::-1] for w in text.split(' '))
推荐阅读
- node.js - node.js同时修改response和store request
- android - Google Play - 尽管存在于应用程序设备目录中,但特定手机型号的 Android 应用程序未显示在商店中
- rotation - 计算给出顶点的旋转角度
- cron - 如何确保一个 cronjob 在另一个 cronjob 完成后运行?
- docker - ddev:更改 docker bridge 网络 ddev_default 的 IP 范围
- python-3.x - 当 Appium 不想要时调出键盘?
- node.js - NodeJS:如何将图像大小与 base64 图像一起使用?
- ubuntu - Ubuntu Preseed i386 UEFI PC 无法尝试安装 64 位 -> grub-efi-amd64-signed
- c# - 如何获得通过 Request.Form 收到的值
- javascript - AS/400 数据队列是否可以访问 node-jt400?(javascript)