Lesson 5. String Concatenation

One way you can change the value of a variable if it is a string value is to take it and smoosh it together with another string. This is called string concatenation and it comes in handy when you need to do things like build file paths.



When you assign a string value to a variable, you let Python know it is a string by surrounding it in quotes. You can use single quotes or double quotes. Just be sure to be consistent. As you can see below, spaces are signified by a space in between two quotes.

name = 'Bob'


name = name + ' ' + 'Wakefield'


Building File Paths

At some point you are probably going to need to move files around on a machine. Some Python methods require that you specify a file name while others just need a directory.

In either case, you want to build a string out of your file path in such a way that you get maximum flexibility out of the whole string. You do that by breaking up the file path into things that change and things that stay the same.

In the variables tutorial, you saw the sophisticated way to do this. I am going to show you a more brute force approach.

See how we break the string down so it is three component parts? In the real world, you will frequently write processes where the file name will change as you loop through a directory. I have simulated that here by reassigning the variable file_name to a new value.

Also notice how I have written the double backslashes. That is because the backslash has special meaning in Python. The backslash is used to denote that a special character is coming like \n which represents the ASCII linefeed value. The backslash escapes the n so the Python interpreter knows that \n means LF and not just the literal string '\n'.

Since backslash is the escape character, putting another backslash in front of a backslash “escapes” the first backslash and now the Python interpreter will know to treat the initial backslash like any other string.

website_projects_dir = '\\User\\Directory\\Projects\\Website'
tutorial_images_dir = '\\Copy\\Academics\\Tutorials\\images'
file_name = '\\sql.jpg'
abs_file_path = website_projects_dir + tutorial_images_dir + file_name


file_name = '\\python.jpg'
abs_file_path = website_projects_dir + tutorial_images_dir + file_name


Now you try it!

Don't copy and past. Type the code yourself!

Last updated