Reputation: 17
I'm trying to write a function that will replace a word in a sentence (which are two separate strings) with "-". It works but I can figure out how to use len to make it so that it will print the correct amount of dashes for the number of characters in the word.
I have been using str.replace() but I can't figure out how to properly work in len(word) into the function so that it will print the correct number of dashes.
sentance=("what is tomorrow's date?")
word="what"
def replaceWord():
print (sentance.replace(word,"----",))
replaceWord()
Upvotes: 0
Views: 939
Reputation: 1065
You have already got your answer. But, here I give you another way to achieve your goal. In this way, you can delibaretly choose your own separtor (e.g '-', '*', '/', etc.).
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?
Upvotes: 0
Reputation: 19
Just multiply the dash string for the len of the word like this
dash = '-'
wl = len(word)
string_to_replace = dash * wl
Upvotes: 0
Reputation: 325
Try:
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)
In python, is possible to multiply a string for a number to obtain that string repeated.
Upvotes: 3