python - 如何提取奇数字符长度的单词的后半部分

标签 python

我正在尝试做一个翻译器:

  • 如果单词长度为奇数,则会交换单词的后半部分,将中间的字符与前半部分保持在其位置。
  • 如果单词的长度是偶数,则会将单词的后半部分与前半部分交换。

如何制作才能将单词的后半部分(将中间字符保持在之前的位置)与前半部分交换?

phrase = input("Phrase: ")

if len(phrase.split()) > 1:
    WORDS = phrase.split()

    if len(WORDS[0]) % 2 != 0:
        print(WORDS[0][-(len(WORDS) / 2 - 1):])

最佳答案

word = "abcde"
if len(word) % 2 != 0:
    print(word[len(word) // 2 + 1:] + word[len(word) // 2] + word[:len(word) // 2])
else:
    print(word[len(word) // 2:] + word[:len(word) // 2])

输出:

"decab" # for word = "abcde"
"cdab" # for word = "abcd"

如果你想保留cab,那么你只需要一行,无论它是奇数还是偶数:

word = "abcde"
print(word[len(word) // 2 + 1:] + word[:len(word) // 2 + 1])

输出:

"deabc"

关于python - 如何提取奇数字符长度的单词的后半部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56174715/

相关文章:

python - 如何使用python获取orient db中顶点的边缘对象数据

Python - 如何将父子转换为嵌套字典

python - 根据用户输入在运行时合并列表

python - 如何在 pandas unstack 之前动态重命名列?

python 3 : Removing an empty tuple from a list of tuples

python - 如何选择深度嵌套的键 :values from dictionary in python

python - 比较列表中的多个唯一字符串

python - Pygame 没有在窗口中显示任何内容

python - 读取 UI 文件并连接按钮、文本等元素

python - 当函数返回时停止 SIGALRM