【问题标题】:String handling in PythonPython中的字符串处理
【发布时间】: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)。这应该比试图操纵第二个参数更简单。

标签: python arrays string


【解决方案1】:

条件表达式是贪心的,像你写的一样解析

Sentence = Sentence[:x] + \
           ("\n" if Sentence[x] == " " else "-\n" + Sentence[x:])

因此,您正在执行以下两种操作之一:

  1. Sentence[:x] + '\n'如果你找到空间
  2. Sentence[:x] + "-\n" + Sentence[x:] 如果您发现其他角色。

请注意,案例 1 缩短了您的句子不正确,但您的 range 对象基于原始正确列表。

解决方法是用括号正确定义条件表达式:

for i in range(1, int(len(Sentence)/40)+1):
    x = i*40
    c = Sentence[x]
    Sentence = Sentence[:x] + (f"\n" if c == " " else f"{c}-\n") + Sentence[x+1:]
    #                         ^                                ^

【讨论】:

  • 这将修复错误,但我怀疑修改后的代码会产生预期的结果。
  • 我认为它会被解析为Sentence = (Sentence[:x] + "\n") if Sentence[x] == " " else ("-\n" + Sentence[x:])?用'3' + '5' if 0 else '99 + 7' 测试,返回'99 + 7'
  • @SCKU 我认为你是对的,因为+Python operator precedence 中高于if-else
  • 是的,我并没有真正检查确切的优先级,只是 Sentence 随着循环的进行而变得更短。我认为修改后代码的主要问题是它替换 Sentence[x]-"\n",而不是在之后插入连字符 Sentence[x]
【解决方案2】:

这个问题一开始可能并不明显,但是当您开始查看字符串连接中间的if 语句时,您就会明白。只需关注以下一行:

Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]

Python 会像这样解析这个语句:

Sentence = (Sentence[:x] + "\n") if Sentence[x] == " " else ("-\n" + Sentence[x:])

仔细注意括号。这正是变量Sentence 保存的字符串长度在每次触发IndexError 异常的迭代后减小的原因。因此,为了解决这个问题,我们必须明确告诉 Python 我们期望什么。所以,可以这样写:

Sentence = Sentence[:x] + ("\n" if Sentence[x] == " " else "-\n") + Sentence[x:]

【讨论】:

  • 为什么 python 不解析语句如:Sentence = (Sentence[:x] + "\n") if Sentence[x] == " " else ("-\n" + Sentence[x:])?
  • @SCKU 我的错。你说的对。我会编辑它。感谢您指出这一点!
【解决方案3】:
string = "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."
stc = ""

for j in range(1 + len(string) // 40):
    stc += string[j * 40:40 * (j + 1)] + "\n"

print(stc)

【讨论】:

  • 我认为这不能处理- 字符,对吧?
猜你喜欢
  • 2016-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多