簡體   English   中英

替換 python 3 中字符串中的單詞

[英]Replacing a word in a string in python 3

我正在嘗試編寫一個 function ,它將用“-”替換句子中的一個單詞(這是兩個單獨的字符串)。 它可以工作,但我可以弄清楚如何使用 len 來制作它,以便它為單詞中的字符數打印正確數量的破折號。

我一直在使用 str.replace() 但我不知道如何在 len(word) 中正確工作到 function 以便它打印正確數量的破折號。

sentance=("what is tomorrow's date?")
word="what"

def replaceWord():
        print (sentance.replace(word,"----",))

replaceWord()

嘗試:

def replaceWord(s, w):
    word_len = len(w)
    dashes = '-' * word_len
    print(s.replace(w,dashes));

s = "what is tomorrow's date?"
w = "what"
replaceWord(s, w)

在 python 中,可以將字符串與數字相乘以獲得重復的字符串。

你已經得到了你的答案。 但是,在這里我給你另一種方法來實現你的目標。 這樣,您可以故意選擇自己的分隔符(例如'-'、'*'、'/'等)。

def replaceWord(sep, word, sentence):
    """
        :param sep: That is the separator.
        :param word: That is the work to replace.
        :param sentence: That is the sentence.
    """
    len_word = len(word)
    replacer = sep * len_word
    print(sentence.replace(word, replacer))

sentence = "what is tomorrow's date?"
word = "what"
sep = "-"  # you can change it
replaceWord(sep, word, sentence)

Output:

---- is tomorrow's date?

只需將破折號字符串乘以這樣的單詞的 len

dash = '-'
wl = len(word)
string_to_replace = dash * wl

暫無
暫無

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

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