簡體   English   中英

Python - 替換部分字符串

[英]Python - Replacing parts of a string

我必須創建猜測行,用戶可以在其中猜測格式如下的較大單詞的子詞:

>>> create_guess_line(2, 8) 
’Guess 2 | - | * | * | * | - | - | - | - |’

其中需要猜測的子猜測用星號表示,並由給定的元組定義:

GUESS_INDEX_TUPLE = (
    ((0,1),(2,4),(2,4),(3,5),(2,5),(0,5)),                  # word length 6
    ((0,1),(1,2),(4,6),(2,5),(3,6),(2,6),(0,6)),            # word length 7
    ((0,1),(1,3),(4,7),(3,5),(3,6),(5,7),(2,7),(0,7)),          # word length 8
    ((0,1),(1,3),(4,7),(3,5),(3,6),(5,7),(3,7),(2,8),(0,8))     # word length 9
)

我如何將星號放在正確的位置? 到目前為止,這是我的嘗試:

def create_guess_line(guess_no, word_length):
    WALL_VERTICAL = ' | '
    WALL_HORIZONTAL = ' - '
    blanks = (WALL_VERTICAL + WALL_HORIZONTAL) * word_length + WALL_VERTICAL
    subguess = blanks.replace(WALL_HORIZONTAL, ' * ')
    index1 = GUESS_INDEX_TUPLE[word_length - 6][guess_no -1][0]
    index2 = GUESS_INDEX_TUPLE[word_length - 6][guess_no -1][1]
    blanks = blanks[0:index1] + subguess + blanks[index2+1:word_length]
    print ('Guess ' + str(guess_no) + blanks)

我得到星號,但太多了。 我假設它是由於將空格乘以字長而搞砸了,但我不確定如何以不同的方式合並字長。

您遇到的問題是此行創建的字符串太長:

blanks = (WALL_VERTICAL + WALL_HORIZONTAL) * word_length + WALL_VERTICAL

這里word_length是 8,但你只需要 3 個星號。

一種更簡潔的方法是制作一個-*字符數組,然后加入它們。 這將允許您進行切片分配,例如:

blanks[index1: index2] = ['*'] * (index2 - index1)

如果您總是要用元組中的第二個數字進行切片,您可以考慮在數據本身中向它添加一個(我已經在此處的代碼中完成了)。 在這個例子中,我用字典替換了你的元組列表,只是為了讓這個例子更容易理解

GUESS_INDEX_TUPLE = {
   6: ((0,1),(2,4),(2,4),(3,5),(2,5),(0,5)),                  # word length 6
   7: ((0,1),(1,2),(4,6),(2,5),(3,6),(2,6),(0,6)),            # word length 7
   8: ((0,1),(1,3),(4,7),(3,5),(3,6),(5,7),(2,7),(0,7)),      # word length 8
   9: ((0,1),(1,3),(4,7),(3,5),(3,6),(5,7),(3,7),(2,8),(0,8)) # word length 9
}

def create_guess_line(guess_no, word_length):
    WALL_VERTICAL = ' | '
    WALL_HORIZONTAL = ' - '

    blanks = [WALL_HORIZONTAL] * word_length
    
    index1, index2 = GUESS_INDEX_TUPLE[word_length][guess_no - 1]
    index2 += 1
    
    blanks[index1: index2] = ['*'] * (index2 - index1)
    print (f'Guess {guess_no}'
           f'{WALL_VERTICAL}'
           f'{WALL_VERTICAL.join(blanks)}'
           f'{WALL_VERTICAL}'
    )

create_guess_line(2, 8)
# Guess 2 |  -  | * | * | * |  -  |  -  |  -  |  -  |

暫無
暫無

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

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