sombat92
sombat92

Reputation: 109

How to extract the second half of a word with an odd character length

I am trying to make a translator:

How do I make it so that I can swap the second half of a word (keeping the middle character in its position that it was before) with the first?

phrase = input("Phrase: ")

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

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

Upvotes: 2

Views: 80

Answers (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])

Output:

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

If you want to keep the c with ab then you only need one line regardless of if it is odd or even:

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

Output:

"deabc"

Upvotes: 2

Related Questions