python - 创建定义以替换 Python 句子中的单词

标签 python python-3.x

我知道如何在不使用替换函数的情况下替换普通 for 循环中的单个字母,但我不知道如何在具有 3 个参数的定义上执行此操作。每个例子

def substitute(sentence, target, replacement)

基本上就像 substitute("The beach is beautiful", "beach", "sky") 并返回 The sky is beautiful.在不使用替换或查找功能的情况下如何做到这一点? 谢谢

def replace_word(sentence, target, replacement):
newSentence = ""
for target in sentence:
    if target in sentence:
        newSentence += replacement
        print(newSentence)
    else:
        True
    return newSentence

最佳答案

这是一种方法。

def replace_word(sentence, target, replacement):
    newSentenceLst = []
    for word in sentence.split():
        if word == target:
            newSentenceLst.append(replacement)
        else:
            newSentenceLst.append(word)
    return ' '.join(newSentenceLst)

res = replace_word("The beach is beautiful", "beach", "sky")

# 'The sky is beautiful'

说明

  • 缩进在 Python 中至关重要。了解如何正确使用它。
  • 使用 str.split 将句子拆分为单词。
  • 初始化列表并通过 list.append 将单词添加到列表中。
  • 如果该单词等于您的目标,则通过 if/else 使用替换。
  • 最后使用 str.join 将单词与空格连接起来。

关于python - 创建定义以替换 Python 句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49719514/

相关文章:

python - 如何使用numpy在for循环中向量化矩阵和?

python Selenium : Explicitly wait for one of two elements to be loaded

python - 通过更改窗口大小来调整包含图像的多个标签的大小

java - 在 python 中使用它们将 2 个参数从 Java 传递到 Python

python-3.x - Pydrive:如何上传大文件或分块上传?

python - 如何统一扩展列表以包括外推平均值?

python - 当数据重复时如何用 pandas 或 numpy 数组检测下降?

python - 使用with语句和imaplib时需要调用close、logout

python-3.x - 从日期时间索引输出唯一年份集

python-3.x - 如何选择 Pandas 中每个唯一记录的最后 5 行