簡體   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