+ 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!

21st Sep 2020, 10:27 PM
David
David - avatar
5 Respostas
+ 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.
21st Sep 2020, 10:48 PM
David
David - avatar
+ 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"
22nd Sep 2020, 9:02 AM
Lothar
Lothar - avatar
+ 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
21st Sep 2020, 10:36 PM
Namit Jain
Namit Jain - avatar
+ 3
David 👍🙂
21st Sep 2020, 11:01 PM
Namit Jain
Namit Jain - avatar
+ 1
Lothar i really appreciate you letting me know and for providing the code. i made the adjustments. thanks again!
23rd Sep 2020, 6:23 PM
David
David - avatar