我試圖在 python 中使用 mod 但出了點問題
我的代碼:
def wrap(string, max_width):
result = ''
for i in range(len(string)):
result = string[i]
if i % max_width-1 == 0:
result = '\n'
return result
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
我的輸入:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
4
我的輸出:
AB
CDEF
GHIJ
KLMN
OPQR
STUV
WXYZ
但我的預期輸出是:
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
我找不到什么問題,除錯器似乎給出了錯誤的結果
uj5u.com熱心網友回復:
對于 4 次換行,您的資料如下所示:
letter A B C D E F G H I J K L M N O ...
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
modulo 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 ...
mod(idx 1) 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 ...
因此,您想在模等于max_width-1(此處為 3)時換行,或者在modulo(index 1)等于0時更容易獲得:
def wrap(string, max_width):
result = ''
for i in range(len(string)):
result = string[i]
if (i 1) % max_width == 0:
result = '\n'
return result
print(wrap('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4))
輸出:
ABCD
EFGH
IJKL
MNOP
QRST
UVWX
YZ
uj5u.com熱心網友回復:
您可以使用 enumerate 來獲取字符及其位置。您還可以告訴它從 1 開始,這將使模運算在適當的中斷索引上作業:
def wrap(string, max_width):
result = ''
for i,c in enumerate(string,1):
result = c
if i % max_width == 0:
result = '\n'
return result
或者,您可以使用跨步下標將字串分解為塊并使用連接組裝它們:
def wrap(string, width):
return "\n".join(string[i:i width] for i in range(0,len(string),width))
或者將邏輯組合成一個單一的理解,提供給連接函式:
def wrap(string, width):
return "".join(c "\n"[i%width:] for i,c in enumerate(string,1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419289.html
標籤:
上一篇:如何在Python中計算平方根?
