我有一个长度应为 3 的多行字符串。但是,空格卡在一个或多个字符串中,我想删除它们:
s = '''123
4 56
7 8'''
print(s)
lines = s.splitlines()
for idx, line in enumerate(lines):
for _ in range(len(line) - len('123')):
lines[idx] = line.replace(' ', '')
s = '\n'.join(lines)
print(s)
123
4 56 # problematic line
7 8
123
456 # fixed line
7 8 # this line should not change, as the white-space here does not make the line longer than length 3
这给了我想要的输出(即所有行的长度都是 3(我不想删除任何不违反长度 3 规则的空格),并且只有白色-空格被删除了)但是有更好的方法吗?
请您参考如下方法:
您可以将 count 作为参数传递给 str.replace 以指定最大替换量。
列表理解也可用于缩短代码。
s = '''123
4 56
7 8'''
lines = [line.replace(' ', '', len(line) - 3) for line in s.splitlines()]
s = '\n'.join(lines)
print(s)
请注意,负数 count 被简单地解释为 0,因此可以使用 len(line) - 3,尽管它可能返回负值。
输出
123
456
7 8
