Coding Journal

My journey to become a Full Stack Developer

cover image

Replacing characters in a string - Python kata

May 10, 2020, 7:50 p.m.

Since I started learning more JavaScript I stopped using Python and now I can observe how much I've forgotten so far. I want to know and be more fluent in both languages so I decided to make myself a small challenge and solve at least one task on Codewars or Edabit a day using Python and JavaScript. And take notes. And publish some of them. I will start with the easier ones.

So today's task is especially nice for me as I'm Polish. It is about changing Polish letters with diacritics into letters without them in a given string.

This is the Python version of the exercise. 

We can use a nice method called .replace(). Strings are immutable in Python, it means we cannot change them, but this method makes and returns a copy of a string.

This method requires a string, an old value and a new value. 

string.replace(old_value, new_value)

If I would like to have an English version of my surname I could use it like this:

and now I could print it out

and the output should be: 
"Roslaniec"

But we want to use it on different strings and more old and new values. 

We need to store those old and new values. In Python, we can use dictionaries. 

What is a Python dictionary?

It's an unordered collection of items. Each item consists of a key : value pair. We can think about keys like about indexes in lists. But in dictionaries they don't have to be integers, they can be different data types, for example, strings what is very handy in that task. 
The key: value pairs are put into braces {} and each pair is divided with comma. 

First I assign the dictionary to a variable <code>`letters`</code> to store Polish letters with diacritics and their equivalents without diacritics.

As I wrote earlier, the keys can be used in a similar way as indexes in lists, so we access the value of given key writing simply:

and the output will be the letter "a". 

We will use this method as well as dict.keys() method to get access to keys and their values. 
If we want to have all the keys printed we will write:

And the output is 
ą
ć
ę
ł
ń
ó
ś
ź
ż

How can we use it in our task?

We have to go through each character of a given string, check if the characters are the same as keys in our dictionary and if they are the same we want to replace them with values from the dictionary. 

Now we can put it into a function

Let's check if it works printing out the function:

The whole working code is available here:
https://repl.it/@maknetaRo1/ScientificPristineQuotes

Tagged in : kata

my photo

written by

Makneta

Avid learner, Python / Django and CSS Art ethusiast.

Similar posts

All posts