用上的另一个字符替换一个字符序列

2024-09-29 19:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符序列'----',我想用“jaillir”中正确范围内的每个字母替换其中的每个'---'。你知道吗

我该怎么做? 这是我的密码

import random

with open ("lexique.txt", "r", encoding= "utf8") as a:
     words = []
     letters = []
tirets= []
for line in a:
    ligne = line[:-1]
    words.append(ligne)
choix = random.choice(words)
tiret = ('-'* len(choix))
print(tiret)
print(choix)
accompli = False
while not accompli:
    lettre = input("Entrez une lettre du mot ")
    for t in range(len(tiret)):
        if lettre in choix:
            tiret.replace(tiret[t], lettre[t])
        print(tiret)

Tags: inforlenline序列random字符words
1条回答
网友
1楼 · 发布于 2024-09-29 19:22:34

我认为您需要修复文件读取代码,尽管这不是问题,如下所示:

with open('lexique.txt', r) as f:
    text = f.read() # get file contents

接下来用一个单词替换,我假设您的文本中的破折号将永远与单词长度相同,因此:

word = 'word' # any string e.g. word
dashes = '-' * len(word)

所以现在可以使用python的字符串.替换方法如下:

text = text.replace(dashes, word) # every time it finds the sequence of dashes it will be replaced by your word

使用for循环(逐步替换):

word = 'word' # any word
length = len(word)
temp = ''

for i, letter in enumerate(text):
    if letter == '-':
        if i + len(tempword) < len(text):
            characters = [True if l == '-' else False for l in text[i:i + len(tempword)]]
            if not(False in characters):
                new += tempword[0]
                if len(tempword) > 1:
                    tempword = tempword[1:]
                else:
                    tempword = word
            else:
                new += letter
    else:
        new += letter

print(new)

相关问题 更多 >

    热门问题