首页 > 解决方案 > 用另一个字符替换一个字符序列

问题描述

我有一个字符序列'-------',我想用正确范围内的'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)

标签: pythonpython-3.xpython-requests

解决方案


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

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

接下来用一个单词替换 ---- ,我假设您的文本中的破折号只会与单词的长度相同,所以:

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

所以现在你可以像这样使用 python 的 string.replace 方法:

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)

推荐阅读