将单词切成两半

问题描述

该任务要求我将单词切成两半然后反转。不使用if语句。

但是,如果字母数量不均匀,其余字母必须坚持单词的前半部分。不是第二个像python那样自动运行的

我成功地将单词切成两半并将其反转。我尝试了多种方法,但是直到现在,我还没有找到一种方法来剪去这封信并将其放在前半部分后面。

如果我使用名称“ Boris”并按原样运行程序,则输出将为“ risBo”,并且我必须说“ 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

解决方法

//是楼层划分运算符。如果您将整数除以2,则意味着它将始终四舍五入。一种快速而又四舍五入的方法是在被2潜水之前只添加一个:

eerste_helft = woord[0:(len(woord) + 1)//2] #I cut the first half

tweede_helft = woord[(len(woord) + 1)//2:] #and cut the second

例如,7 // 2等于3。现在它等于4,因为(7 + 1) // 2 == 4

即使8 // 2(8 + 1) // 2都仍然等于4,所以数字也不会改变。

,

由于需要除以2后的最大值,因此可以这样使用:

half1 = word[:len(word)+(len(word)%2==1)]
half2 = word[len(word)+(len(word)%2==1):]
print (half2+half1)