0

Code:

str="Hello World"         
for i in range(len(str)):                  
  str[i]=str[len(str)-i]    
print(str)

This corresponds to an error in Python. What would be the right way to implement this?

ZdaR
  • 22,343
  • 7
  • 66
  • 87
Sourav
  • 43
  • 5

3 Answers3

3
  1. In Python, strings are immutable. You can't reassign individual characters.
  2. str is not a good variable name because it masks the built-in function str().
  3. It looks like you want to reverse the string:

string = "Hello World"
reversed_string = string[::-1]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Thank you, but i actually wanted the mirror image of the string along its center. Can you help? – Sourav Jun 03 '15 at 04:33
  • 1
    Mirroring both ends along the center is equivalent to reversing it. If you want something else, please clarify the expected input and output. – TigerhawkT3 Jun 03 '15 at 04:36
1

try to following:

string = "Hello World"
print string[::-1]
print ''.join(reversed(string))
Haresh Shyara
  • 1,826
  • 10
  • 13
0

In fact, I think the key problem of you is that you don't understand that string in python is immutable, yet you can read str[i] but this don't mean that you can change str[i],never do this: one_string = "..." one_string[i] = ".." remember one_string[i] is read only. You can just use some standard lib funcion to replace part of the string, but some thing like one_string[i] = "..." is absolutely wrong.

cyrusin
  • 21
  • 3