把一个词切成两半
Slicing a word in half
任务要求我把一个词对半切开,然后倒过来。不使用 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
//
是楼层除法运算符。如果你将整数除以二,这意味着它总是向下舍入。一种 quick-and-dirty 使其四舍五入的方法是在乘以二之前只加一个:
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。
由于除以二后需要取上面的值,所以可以这样使用:
half1 = word[:len(word)+(len(word)%2==1)]
half2 = word[len(word)+(len(word)%2==1):]
print (half2+half1)
任务要求我把一个词对半切开,然后倒过来。不使用 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
//
是楼层除法运算符。如果你将整数除以二,这意味着它总是向下舍入。一种 quick-and-dirty 使其四舍五入的方法是在乘以二之前只加一个:
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。
由于除以二后需要取上面的值,所以可以这样使用:
half1 = word[:len(word)+(len(word)%2==1)]
half2 = word[len(word)+(len(word)%2==1):]
print (half2+half1)