Change a character in a string

Let's say you have the following string (which just so happens to be a URL, which isn't important):

There's a problem with this URL, the .uk component of the address has mistakenly been entered as .ui. Let's fix this with Python.

First, we take the URL and pass it as a string into the list() function.

s = list('

Then, we identify where the offending character (in this case, i) appears (it's 22nd character). Bearing in mind that Python is zero-indexed, we can target it as the 21st item in the list and change the value to k like so:

s[21] = 'k'

No that the character has been corrected, we can join() the list back together to form the corrected string:

s = "".join(s)

Reverse a string

This is one of those things that sounds quite simple, but seems to generate quite a lot of discussion on the best way to do it. If you're interested in diving into that discussion, take a look at this StackOverflow question and the answers. 

If, however, all you care about is actually reversing a string with Python, here's a couple of ways to do it. 

Let's say we have a string:

mystring = 'Hello my name is Daniel

Method 1

This method uses reverse() and has the benefit of being comparatively readable in comparison to Method 2.

print (''.join(reversed(mystring)))


leinaD si eman ym olleH

Method 2

This method uses extended slice, which essentially slices one character of the end of the string in successive steps. Not as obvious as method 1, if you ask me. 

print (mystring[::-1])


leinaD si eman ym olleH