+ 1
replacing a string with a character
Hi Everyone, Does anyone know how to change a string to a character? for example, If I wanted to check if a specific word was in a paragraph and if it was, change that word to the same length, but 'X's. If that word I was changing was 'algorithms', the output would be XXXXXXXXXXX. I know I have to check each character of the word and if it's not an X, replace it, but I'm a bit stuck on how to do so. Appreciate any help. Thanks!
5 Réponses
+ 1
Namit Jain thank you Namit for answering. I normally do show my code but its a bit of a mess. thanks again. it works.
+ 6
You should be careful using a character based replacement. by using the input shown down here, the result will be: >>> "take this flower XXX keep it with your hXXXs". the replacement has also modified a part of a word.
sentence = 'take this flower and keep it in your hands'
to_replace = 'and'
replacement = 'X'
word_lst = sentence.split()
res = [word if word != to_replace else replacement * len(word) for word in word_lst]
print(' '.join(res))
result will be: >>> "take this flower XXX keep it in your hands"
+ 4
It would be better if you showed your attempt 🙃
But anyways, you can refer to this code!
https://code.sololearn.com/cG41pxBn37Xx/?ref=app
+ 3
David 👍🙂
+ 1
Lothar i really appreciate you letting me know and for providing the code. i made the adjustments. thanks again!