我已经成功地创建了一个函数,该函数接受一个字符串和一个int,并返回一个从参数字符串派生的新字符串,但是重复/删除了一些字符。每个字符都乘以它的ord mod x。我不知道我如何才能阻止它做它的空白,虽然
下面是整个代码块,包括doctest:
def balloon_string(string, x):
"""
>>> balloon_string('abcdef', 4)
'abbccceff'
>>> balloon_string('A great day!', 4)
'Agggrreaay!'
>>> balloon_string('ABC 1234', 3)
'AAC 1224'
"""
l = []
for ch in string:
l.append(str(ch*(ord(ch)%x)))
return ''.join(l)
我从中得到的结果是:
Expecting:
'abbccceff'
ok
Expecting:
'Agggrreaay!'
ok
Expected:
'AAC 1224'
Got:
'AAC 1224'
正如你所见,最后一个有一个额外的空间,我不知道如何摆脱它
简单:检查
ch
是否是空格,如果是,则不要执行加倍操作:或者,你可以做一个很酷的一行:
您可以在一行中完成这一切,如下所示:
相关问题 更多 >
编程相关推荐