+ 1
how to replace a number with a word in a while loop?
hi! I'm still a beginner in python and I have to write a program with a while loop in which I replace a number with a word (f.e.: 1 = one) in a string (f.e.: 2er41g = 2er4oneg). i can do it with a for loop but I can't change it without getting an error :( and I'm not allowed to use replace() or similar modules. Thank you for your help!
5 Respuestas
+ 2
Oh, your code was pretty good! The idea of using the result variable is perfect! There were probably some typos. I tidied it up a little bit.
user_string = "input9"
result = ""
for char in user_string:
if char == "9":
result += "nine"
else:
result += char
print(result)
Now to change it to while, instead of directly iterating over the characters of the string, we have to use an index i and access the character at position i of the string. i will be initialized as zero and increase by 1 at each step until it reaches the length of the string.
user_string = "input9"
i = 0
result = ""
while i < len(user_string):
if user_string[i] == "9":
result += "nine"
else:
result += user_string[i]
i += 1
print(result)
Does that make sense? Let me know. ☺
+ 3
Can you please share your code with for loop? Then we can help you fix the error, and change it to while loop too ;)
Thanks!
+ 2
You're welcome, broadenyourmindbnr 😊
+ 1
Sure!
user_input = input9
x = user_input #thats an input / string
result = ""
for i in user_string:
if i == "9":
i = "nine"
result += i
print(result)
I'm looking for the same output in a while loop ;)
Thanks!
+ 1
Yes! Thank you so much! And you were sooo fast!!
I think I understand it now much better!!
Thanks!!
Makes sense and very helpful! 🤗