如何在乘法和模中不乘空间?

2024-09-24 00:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经成功地创建了一个函数,该函数接受一个字符串和一个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'

正如你所见,最后一个有一个额外的空间,我不知道如何摆脱它


Tags: 函数字符串mod参数stringokch字符
2条回答

简单:检查ch是否是空格,如果是,则不要执行加倍操作:

if ch == ' ' and ord(ch)%x != 0:
    l.append(ch)
else:
    l.append(ch*(ord(ch)%x))  # since ch is already a str, casting this back to str is unnecessary

或者,你可以做一个很酷的一行:

l.append(ch*(ord(ch)%x) if (ch != ' ' or ord(ch) % x == 0) else ch)

您可以在一行中完成这一切,如下所示:

def balloon_string(string, x):
    return ''.join((c * (ord(c) % x)) if c != ' ' else c for c in string)

print(balloon_string('abcdef', 4))
# abbccceff
print(balloon_string('A great day!', 4))
# A gggrrea ay!
print(balloon_string('ABC 1234', 3))
# AAC 1224

相关问题 更多 >