[英]Python - How to returns a string in which each digit is replaced by the corresponding number of exclamation marks (!)
Hi I just started out coding and came across this question on my workbook:嗨,我刚开始编码,在我的工作簿上遇到了这个问题:
Write a function (called excited_string) that takes a single string, s, as an argument and returns a string in which each digit is replaced by the corresponding number of exclamation marks (.).编写一个 function(称为excited_string),它将单个字符串s 作为参数并返回一个字符串,其中每个数字都替换为相应数量的感叹号(.)。
What the code should do:代码应该做什么:
>>> 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!!!'
My code so far:到目前为止我的代码:
def excited_string(s):
new = ''
for ch in s:
if ch.isalpha() is False:
print(int(ch) * '!')
Thanks for any guidance!感谢您的任何指导!
edit: I got:编辑:我得到:
!
!!
!!!
then I got error for excited_string(" 1 2 3 4 5") due to the ' ' (spaces).然后由于''(空格),我得到了excited_string(“1 2 3 4 5”)的错误。
You can use string.join() and a list comprehension您可以使用 string.join() 和列表理解
s = "1234"
for ch in s:
if ch.isalpha() is False:
print("".join("!" for i in range(int(ch))))
Outputs:输出:
!
!!
!!!
!!!!
Usually, when instructions mention "a function returns", you want to use the return
syntax.通常,当指令提到“a function 返回”时,您希望使用return
语法。 The return
syntax will end a function's execution and "give back" whoever called it the value written after return
. return
语法将结束函数的执行,并“归还”任何调用它的人return
之后写入的值。
def func1():
x = 5
return x
def gimme():
the_value = func1()
print(the_value)
gimme()
5
You started off well declaring new
being a variable meant to hold the final value.您开始很好地声明new
是一个旨在保存最终值的变量。 And you were correct with the syntax int(ch) * '!'
你的语法是正确的int(ch) * '!'
. . Strings support the multiplication operator vs a number字符串支持乘法运算符与数字
x = 'c' * 5
print(x)
ccccc
Now you just need to figure out how to concatenate each piece of string to the final result, in new
, before return
-ing it.现在您只需要弄清楚如何在new
中将每段字符串连接到最终结果,然后再return
它。 Don't worry about anything fancy, try simple and straightforward first to exercise problem solving.不要担心任何花哨的事情,先尝试简单直接地解决问题。
Good luck!祝你好运!
This should work:这应该有效:
result = ''.join( ['!'*int(c) if c.isdigit() else c for c in a] )
Testing:测试:
>>> 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.