使用结构更换在for循环中

2024-10-05 19:10:31 发布

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

我正在做一个任务,要求我更改下面的代码,以便第4行使用蓝藻str.isalnum而第5-7行变成只使用一行结构更换. 在

s = 'p55w-r@d'
result = ''
for c in s:
    if(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
        result += '*'
    else:
        result += c
print(result)

到目前为止,我得到的是:

^{pr2}$

第二个代码的输出需要等于代码1的输出:

p55w*r*d

Tags: 代码inforifnotresult结构else
3条回答

只需添加else部分即可完成:

s = 'p55w-r@d'
result = ''
for c in s:
    if(c.isalnum() == False):
        result += c.replace(c,'*')
    else:
        result +=c 
print(result)

p55w*r*d

在合理的情况下,最能满足任务要求的是:

s = 'p55w-r@d'
result = s  # Note the change here
for c in set(s):  # set(..) is not strictly necessary, but avoids repeated chars
    if not c.isalnum():
        result = result.replace(c, '*')

我知道如何用两条线来做同样的事情:

s = 'p55w-r@d'
print(''.join(map(lambda x: x if x.isalnum() else '*', s)))

输出:

^{pr2}$

相关问题 更多 >