【发布时间】:2013-09-25 18:55:45
【问题描述】:
所以我需要我的程序的输出看起来像:
ababa
ab ba
xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
no dot at the end
The largest run of consecutive whitespace characters was 47.
但我得到的是:
ababa
ab ba
xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
no dot at the end
The longest run of consecutive whitespace characters was 47.
当进一步查看我编写的代码时,我发现 print(c) 语句会发生这种情况:
['ababa', '', 'ab ba ', '', ' xxxxxxxxxxxxxxxxxxx', 'that is it followed by a lot of spaces .', ' no dot at the end']
在某些行之间,有, '',,这可能是我的打印语句不起作用的原因。
我将如何删除它们?我尝试过使用不同的列表函数,但我不断收到语法错误。
这是我制作的代码:
a = '''ababa
ab ba
xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
no dot at the end'''
c = a.splitlines()
print(c)
#d = c.remove(" ") #this part doesnt work
#print(d)
for row in c:
print(' '.join(row.split()))
last_char = ""
current_seq_len = 0
max_seq_len = 0
for d in a:
if d == last_char:
current_seq_len += 1
if current_seq_len > max_seq_len:
max_seq_len = current_seq_len
else:
current_seq_len = 1
last_char = d
#this part just needs to count the whitespace
print("The longest run of consecutive whitespace characters was",str(max_seq_len)+".")
【问题讨论】:
-
什么样的逻辑从
" xxxxxxxx"创建" xxxxxxxx"?? -
附注:
remove方法修改列表并返回None。因此,您应该不执行d = c.remove(''),而只需:c.remove(''),然后c将少一个 空字符串。要通过remove删除所有空字符串,请执行:for _ in range(c.count('')): c.remove('')(顺便说一句:空字符串是'',即引号,没有任何空格。在您的情况下,您删除单个空格字符串:' 'quote-space-quote,你可能得到了一些ValueErrors)
标签: python list whitespace sequence output