【发布时间】:2021-06-19 17:46:57
【问题描述】:
我正在尝试编写一个简短的 Python 函数,通过插入 \n 将长单行字符串分解为多行字符串。当我简单地将\n 插入字符串时,代码工作正常,但是当我插入条件检查以添加连字符时,出现索引超出范围错误。这是我写的代码。
Sentence = "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
for i in range(1, int(len(Sentence)/40)+1):
x = i*40
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
print(Sentence)
这是我收到的错误消息。
Traceback (most recent call last):
File "/media/u1/data/prop.py", line 4, in <module>
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
IndexError: string index out of range
【问题讨论】:
-
range可以采取步骤参数:for x in range(40, len(Sentence), 40)。这应该比试图操纵第二个参数更简单。