+ 1
Hello, i'm beginner and i don't understand why my code don't transform any characters. Thanks for your help.
13 Respuestas
+ 4
Guillaume Pierson okay I see. That happened because replace() replaces all the letters that match the argument. For example
"A, B, C, D".replace(", " , " ")
Outputs "A B C D" (that is, all the commas got replaced.
In your case what happens is
1. init_phrase[i] is 's' and it gets replaced by 'h'
New string : 'hololearn'
2. init_phrase[i] is 'o'. All 'o' get replaced with 'l'
New string : 'hllllearn'
3. (Here is the problem) init_phrase[i] is 'l'. All 'l' get replaced by 'o'.
New string : 'hooooearn'
And so on
So instead of using .replace(), what you can do is change the string to a list (by using list(init_phrase) and iterate through that list. And while in the for loop, you can change the letter at that specific index
init_phrase[i] = ...
+ 3
Justus with all due respect, please from the next time, instead of just giving the solution to the question asker, show them what is the problem in their code and what approach they can use to achieve what they want.
Happy coding!
+ 3
XXX thanks for your explanation. I wanted to try to do it directly on a string but it seems to be harder than I thought.
Justus thanks too but I wasn't looking for a ready made solution but an explanation. And thanks for the technique to make à dict with 2 lists. I was going to get it.
+ 2
Guillaume Pierson it's not harder. It's actually easier. You just have to change the specific index.
For example,
a = [1, 2, 3, 4]
for i in range(len(a)):
a[i] = i ** 2
Now if you print a, the output would be
[1, 4, 9, 16]
You can do the same thing with your string.
And then, at last do
"".join(name_of_the_list)
To convert it to a string.
Feel free to question further.
+ 1
Yes it seems to work but when I give sololearn as input it don't transform "o". It give me hoooovzim instead of hlolovzim.
+ 1
I'll try👍
+ 1
XXX Sorry my english isn't very Good. I wanted to try to do it without string. In others challenges i always do it with list but I wanted to test directly on string. Maybe it's impossible.
0
Guillaume Pierson it seems to work for me. It would be really helpful if you mentioned what you gave as input when the code didn't work.
0
Edited. Works
https://code.sololearn.com/c9gt3HvHg0u8/?ref=app
0
For spaces.
https://code.sololearn.com/cF9zsjHZz9Am/?ref=app
0
But why the last character of string can't be changed in this programm.
If I give input like that.
hello
The output should be like that
svool
But your programm given that output.
svooo
I can't understand your programms mechanism?🤔
0
This programme doesn't really work. XXX give me the reason. This was a test to make it without transform string to list but it's fail. I don't know if it possible.