簡體   English   中英

Python - 如何在每第 n 個字符后將“*”插入字符串

[英]Python - How to insert '*' into a string after every nth character

我目前被困在這個問題上,它需要 2 個 arguments(字符串和一個 int,n),它應該返回一個新字符串,其中每個第 n 個字符(從 0 開始)后跟一個“*”。

我發現了關於堆棧溢出的類似問題,但答案包括我剛開始編碼時不知道如何使用的更高級的編碼函數(如 range()、emurate 等)。

代碼應該做什么:

>>> string_chunks("Once upon a time, in a land far, far away", 5)
'O*nce u*pon a* time*, in *a lan*d far*, far* away*'

到目前為止,我的代碼只打印出字符串中的每 5 個字符:

def string_chunks(string, x):
    new = ''
    for ch in string[::x]:
        new += ch 
    return new

>>>'Ouae nrry'

我不確定是否應該在我的代碼中使用 str.find()/str.split()。 如果有人可以幫助我改進或指導我,那將是一個很大的幫助。 謝謝!

你的例子似乎不正確。 nth position 意味着每個索引都是n的倍數。

但是,如果您的措辭錯誤,您可以隨時移動ncnt以確保它與您想要的 output 匹配。

您沒有在 function 中添加任何開始,只需檢查 position 是否是 x 的倍數,如果yes ,則添加*

def string_chunks(string, x):
    new = ''
    cnt = 0
    for ch in string:
        if cnt%x==0 and cnt!=0: # checking if cnt is a multiple of x and not 0, we don't want to put star at index 0
            new += '*'
        cnt += 1
        new += ch
    return new
string_chunks("Once upon a time, in a land far, far away", 5)

Out: 'Once *upon *a tim*e, in* a la*nd fa*r, fa*r awa*y'

def add_asterisk_every(string, n):
    # Create a list to hold the characters in the new string we'll be creating.
    with_asterisks = []

    # Keep track of how many characters we've passed since the last asterisk was added.
    characters_scanned = 0

    # Iterate through each character of the input string and add each character of the input string to with_asterisks.
    # Once we scan n characters, we'll add an asterisk and restart the counter.
    for character in string:
        if characters_scanned == n:
            with_asterisks.append('*')
            characters_scanned = 0
        characters_scanned += 1
        with_asterisks.append(character)

    # Create the output string from our character list.
    return ''.join(with_asterisks)

print(add_asterisk_every("Once upon a time, in a land far, far away", 5))

產生:

Once *upon *a tim*e, in* a la*nd fa*r, fa*r awa*y

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM