Reputation: 23
The task requires me to cut a word in half and reverse it. Without using the if statement.
However if it has an uneven amount of letters, the remaining letters must stick to the first half of the word. Not the second like python does automatically.
I succeeded in cutting the word in half and reverse it. I tried multiple things but until now I have not found a way to cut the letter and put it behind the first half.
If I used the name 'Boris' and run the program as it is, the output will be 'risBo' and I have to make it say 'isBor'
#input
woord = input("Geef een woord in : ") #here I ask the user to give a word
#verwerking
eerste_helft = woord[0:len(woord)//2] #I cut the first half
tweede_helft = woord[(len(woord)//2):] #and cut the second
#output
print(tweede_helft + eerste_helft) #here I reversed the two halves
Upvotes: 0
Views: 420
Reputation: 8186
Since you need to take the upper value after dividing by two, you can use it like this:
half1 = word[:len(word)+(len(word)%2==1)]
half2 = word[len(word)+(len(word)%2==1):]
print (half2+half1)
Upvotes: 0
Reputation: 24691
//
is the floor division operator. If you're dividing integers by two, this means it'll always round down. A quick-and-dirty way to make it round up instead is to just add one, before diving by two:
eerste_helft = woord[0:(len(woord) + 1)//2] #I cut the first half
tweede_helft = woord[(len(woord) + 1)//2:] #and cut the second
For example, 7 // 2
used to equal 3. Now it equals 4, because (7 + 1) // 2 == 4
.
Even numbers don't change, because 8 // 2
and (8 + 1) // 2
are both still equal to 4.
Upvotes: 1