繁体   English   中英

Python - 如何返回一个字符串,其中每个数字都替换为相应数量的感叹号(!)

[英]Python - How to returns a string in which each digit is replaced by the corresponding number of exclamation marks (!)

嗨,我刚开始编码,在我的工作簿上遇到了这个问题:

编写一个 function(称为excited_string),它将单个字符串s 作为参数并返回一个字符串,其中每个数字都替换为相应数量的感叹号(.)。

代码应该做什么:

>>> excited_string("123")
'!!!!!!'
>>> excited_string(" 1 2 3 4 5")
' ! !! !!! !!!! !!!!!'
>>> excited_string("Wow1 This2 is1 super111 exci2ting")
'Wow! This!! is! super!!! exci!!ting'
>>> excited_string("Wow1 This2 is1 super111 exciting3")
'Wow! This!! is! super!!! exciting!!!'

到目前为止我的代码:

def excited_string(s):
    new = ''
    for ch in s:
        if ch.isalpha() is False:
            print(int(ch) * '!')

感谢您的任何指导!

编辑:我得到:

!
!!
!!!

然后由于''(空格),我得到了excited_string(“1 2 3 4 5”)的错误。

您可以使用 string.join() 和列表理解

s = "1234"
for ch in s:
    if ch.isalpha() is False:
        print("".join("!" for i in range(int(ch))))

输出:

!
!!
!!!
!!!!

通常,当指令提到“a function 返回”时,您希望使用return语法。 return语法将结束函数的执行,并“归还”任何调用它的人return之后写入的值。

def func1():
    x = 5
    return x

def gimme():
    the_value = func1()
    print(the_value)

gimme()
5

您开始很好地声明new是一个旨在保存最终值的变量。 你的语法是正确的int(ch) * '!' . 字符串支持乘法运算符与数字

x = 'c' * 5
print(x)
ccccc

现在您只需要弄清楚如何在new中将每段字符串连接到最终结果,然后再return它。 不要担心任何花哨的事情,先尝试简单直接地解决问题。

祝你好运!

这应该有效:

result = ''.join( ['!'*int(c) if c.isdigit() else c for c in a] )

测试:

>>> a = 'a2b5c2/'
>>> result = ''.join( ['!'*int(c) if c.isdigit() else c for c in a] )
>>> result
'a!!b!!!!!c!!/'
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM