简体   繁体   English

如何在 python 中使用替换 function

[英]How to use the replace function in python

I'm trying to make a function that takes a string from the user and replaces a word in the string with another using the replace function.我正在尝试制作一个 function,它从用户那里获取一个字符串,并使用替换 function 将字符串中的一个单词替换为另一个单词。 I'm new to using the replace function but I have this so far.我是使用替换 function 的新手,但到目前为止我有这个。

def replacer(phrase, *args):
    # Sample:
    # replacer('hello world', ('l', 'r')) --> 'herro worrd'
    outputString = ""
    for char in phrase:
        foundFlag = False
        for arg in args:
            if char == arg:
                outputString += arg[1]
                foundFlag = True
                break
        if foundFlag:
            outputString += char
    return outputString

You don't need to write a custom function for replacing chars in a string python string object has a builtin method called replace() .您不需要编写自定义 function 来替换字符串 python 字符串中的字符 object 有一个名为replace()builtin method

string.replace(s, old, new[, maxreplace])

It returns a copy of a string with all occurrence of sub string old replaced by new.它返回一个字符串的副本,其中所有出现的子字符串 old 都替换为 new。

for eg:-例如:-

string = 'hello world'
new_string = string.replace('l','r', 2)
output==>  herro world

You seem to have mixed up your logic.你好像搞混了你的逻辑。 You are comparing each character with the tuple passed, and you only append to the outputString if the condition matches.您正在将每个字符与传递的元组进行比较,如果条件匹配,您只需将 append 与outputString进行比较。 Make the following changes:进行以下更改:

Change改变

if char == arg:

to

if char == arg[0]:

and

if foundFlag:

to

if not foundFlag:

It will then print:然后它将打印:

herro worrd
from dataclasses import replace


letter = '''Dear <|NAME|>
            you are selected
            Date:<|DATE|> 
'''

name = input("Enter your name\n")
date = input("Enter today's date\n")
letter = letter.replace('<|NAME|>',name)
letter = letter.replace('<|DATE|>',date)
print(letter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM