Search code examples
pythonsymbolic-math

How does the + sign work in python in case of strings?


I'm learning from the 4 hr basic python video from freecodecamp. In the video, there is an example showing how to make a basic translation program by replacing the vowels in a word with the letter 'g'. The code uses a for loop and the plus(+) sign for this.

My difficulty is that I thought the plus sign is used to add strings to each other. Not replace something. It seems counterintuitive. How does it work? I'd be grateful if you direct me towards helpful resources.

The code in the video


Solution

  • You are right about the plus sign. It is used to concatenate strings together. However the program performs "translation" by building a new string from the empty translation = "" while replacing vowels with 'g'.

    for letter in phrase
    

    get each letter in the phrase string and perform an if check on it. If it's a vowel, add 'g' to the empty string. if it's not, add the original letter to it. The end result is the 'translated' new string returned.