gpt4 book ai didi

python - `.split()`如何保存多个空间?

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:00 25 4
gpt4 key购买 nike

例如,我有一个这样的文件:

while True:
if test = 10:
print(a, b)

现在我编写了一个脚本来读取该文件,然后...以随机颜色打印所有单词。这是我的代码:

color = [color for color in range(91, 97)]
with open(sys.argv[1], 'r') as f:
for i in f.readlines():
for w in i.split():
print('\033[{0}m{1}\033[{0};m'
.format(random.choice(color), w), end='')
print(' ', end='')
print()

当然,它正在工作。但是 .split() 没有保存所有的空格,所以输出没有缩进:

while True 
if test = 10:
print(a, b)

现在我的问题是:如何节省空间?

最佳答案

您可以根据 ' ' (空格,而不是 None 按所有空格拆分)进行拆分,并且只打印包含空格以外的任何内容的单词 (为此,您可以简单地检查 w.strip() 是否为空字符串`。示例 -

import random
import sys
color = [color for color in range(91, 97)]
with open(sys.argv[1], 'r') as f:
for i in f:
for w in i.rstrip().split(' '):
if w.strip():
print('\033[{0}m{1}\033[{0};m'
.format(random.choice(color), w), end='')
print(' ', end='')
print()

演示 -

用OP的代码-

←[91mwhile←[91;m ←[92mTrue:←[92;m
←[96mif←[96;m ←[92mtest←[92;m ←[95m=←[95;m ←[95m10:←[95;m
←[92mprint(a,←[92;m ←[93mb)←[93;m

根据上述建议的更改 -

←[93mwhile←[93;m ←[93mTrue:←[93;m
←[94mif←[94;m ←[93mtest←[93;m ←[91m=←[91;m ←[94m10:←[94;m
←[91mprint(a,←[91;m ←[96mb)←[96;m

关于python - `.split()`如何保存多个空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32664179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com