把一个词切成两半

2024-10-01 00:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这项任务要求我把一个词一分为二,然后把它颠倒过来。不使用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

Tags: the方法input数量lenifhere字母
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)

相关问题 更多 >