Ropython4 Ropython4 - 1 month ago 7
Python Question

Check for a string repeated twice, if word is repeated twice return true if not, False

I am using Python and am a beginner. I want my program to check if a word inputted by the user is repeated or not, I know I have to use a for loop to check if the word is repeated or not... using 'in'

word = input("Enter a word:")

def repeatedWord(word):
for "input by user:" in word
return True
else:
return False


I know this doesn't work, but what would work in order for me to know if the user repeated the word or not using a for loop in strings?

It should return
True
if the word consists of some word repeated twice and
False
otherwise.

Examples:

doubleWord("cat") -> False
doubleWord("catcat") -> True
doubleWord("contour"*2) -> True
doubleWord("acatcat") -> False
doubleWord("catcatcat") -> False
doubleWord("catcatcatcat") -> True

Answer

If you rephrase the question, it might be easier to understand how to go about this: Is the first half of the word equal to the second half of the word?

We can use Python slicing syntax to divide the word in half:

  • word[:n]: first n characters of word
  • word[n:]: all the other characters

To get the halfway mark, we divide the length of the word len(word) by 2: we will floor divide so that it is an integer.

The following function will do the trick:

def repeated_word(word):
    n = len(word) // 2
    return word[:n] == word[n:]