From the course: Programming Foundations: Fundamentals

Working with strings - Python Tutorial

From the course: Programming Foundations: Fundamentals

Working with strings

- Let's talk about strings. In programming, whenever we have to deal with text, be it an email address, someone's name, or even an emoji, we use strings. The name comes from the fact that it's a string of characters one after the other. The characters can be letters, numbers, symbols, and even spaces. They're typically represented by beginning and ending quotes. Strings can be passed directly to functions or they can be stored in variables. For example, we can use the print function in Python to display a message on the screen, like, "Hi, there!" Notice that we have the opening and closing double quotes. These let Python know it should print out the characters in between the quotes just as we've typed them. We could also define a variable which contains the same string and we'd get the same result. In fact, with Python, we could use single quotes to create a string as well. But you might be wondering why would I want to use the double quotes version over the single quotes version of strings? Well, it depends on the contents of your string. Let's see what happens when we print out the following string that's wrapped in double quotes. "She said," double quotes, "Unbelievable," double quote, "to him." We receive a syntax error because we've confused Python with our nested double quotes. Instead, we will want to use single quotes to open and close our string. This way, Python knows just what we mean. And the inverse is also true. If we want to use single quotes, or an apostrophe inside of our string, like, "Let's get started," then we would use double quotes at the beginning and end. But keep in mind you don't want to mix single and double quotes together. Something like this print statement where we have an opening double quote and a closing single quote will also lead to a syntax error. When you're first starting out with programming, I recommend using the double quotes version of strings as your go to. For this course, I'll be using double quotes for strings, as it's the most common version that you'll see across languages. Now that you've got a handle on strings, let's put 'em to work in our programs.

Contents