-2

I need to get a user to enter a sentence for an assignment. Using a for loop, I then need to replace all spaces with %20 in order to prep the string to be used as a URL. I cannot for the life of me figure it out.

sentence = str(input("Please enter sentence:"))
space = (" ")

for space in sentence:
    space.replace(sentence, space, "%20", 500)
print(sentence)

This is what I have entered so far but it is completely wrong.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

3 Answers3

2

String in Python can't be modified. The replace() function returns a new string with all the replacements done. You need to assign this result somewhere. So you can do:

sentence = sentence.replace(" ", "%20")

If you want to do it with a loop, you need to build the result in another variable.

new_sentence = ""
for char in sentence:
    if char == " ":
        new_sentence += "%20"
    else:
        new_sentence += char

There's no point in using replace() in the loop.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Replace everything after the first line with print(sentence.replace(" ","%20"))

or, if you really must use a loop:

s = ''
for x in sentence:
    if x == ' ':
        s += "%20"
    else:
        s += x
print(s)
mRotten
  • 447
  • 1
  • 4
  • 11
0

you've got a few problems here:

  1. the variable space that you define before the loop is equal to " " but then you're using the same name for the for loop variable, which is going to iterate through the string the sentence string, in the loop, it's going to use the value defined by the loop.

  2. You're giving the replace method too many arguments, it's a method of the string object so you don't need to pass it the large string to operate on Replace Method

  3. You're using the replace method on the space string and not on the sentence string

Good way to do it in real life:

old = ' '  
new = '%20'

sentence = str(input("Please enter sentence:"))
print(sentence.replace(old,new))

The way your teacher is probably after:

sentence = str(input("Please enter sentence:"))
old = ' '  
new = '%20'
newSentence = ''

for letter in sentence:
    if letter == ' ':
        newSentence += new
    else:
        newSentence += letter


print(newSentence)
Kieran
  • 89
  • 1
  • 13
  • 1
    Hi Kieran, Thanks for your help. Not only does the code work and it is 100% in line with what my lecturer is looking for. it all makes a lot of sense and has really cleared up the problem in my head. thanks :D – k.dochertyy Nov 14 '18 at 09:32
  • No worries mate! Glad I could help – Kieran Nov 16 '18 at 03:18