An Introduction to Working with Strings in Python 3

Introduction

A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Made up of Unicode, strings are immutable sequences, meaning they are unchanging.

Because text is such a common form of data that we use in everyday life, the string data type is a very important building block of programming.

This Python tutorial will go over how to create and print strings, how to concatenate and replicate strings, and how to store strings in variables.

Creating and Printing Strings

Strings exist within either single quotes ' or double quotes " in Python, so to create a string, enclose a sequence of characters in one or the other:

'This is a string in single quotes.'

"This is a string in double quotes."

You can choose to use either single quotes or double quotes, but whichever you decide on you should be consistent within a program.

We can print out strings by simply calling the print() function:

print("Let's print out this string.")

Output

Let's print out this string.

With an understanding of how strings are formatted in Python, let’s take a look at how we can work with and manipulate strings in programs.

String Concatenation

Concatenation means joining strings together end-to-end to create a new string. To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

Let’s combine the strings "Sammy" and "Shark" together with concatenation through a print() statement:

print("Sammy" + "Shark")

Output

SammyShark

If we would like a whitespace between the two strings, we can simply include the whitespace within a string, like after the word “Sammy”:

print("Sammy " + "Shark")

Output

Sammy Shark

Be sure not to use the + operator between two different data types. We can’t concatenate strings and integers together, for instance. So, if we try to write:

print("Sammy" + 27)

We will receive the following error:

Output

TypeError: Can't convert 'int' object to str implicitly

If we wanted to create the string "Sammy27", we could do so by putting the number 27 in quotes ("27") so that it is no longer an integer but is instead a string. Converting numbers to strings for concatenation can be useful when dealing with zip codes or phone numbers, for example, as we don’t want to perform addition between a country code and an area code, but we do want them to stay together.

When we combine two or more strings through concatenation we are creating a new string that we can use throughout our program.

String Replication

There may be times when you need to use Python to automate tasks, and one way you may do this is through repeating a string several times. You can do so with the * operator. Like the + operator, the * operator has a different use when used with numbers, where it is the operator for multiplication. When used with one string and one integer, * is the string replication operator, repeating a single string however many times you would like through the integer you provide.

Let’s print out “Sammy” 9 times without typing out “Sammy” 9 times with the * operator:

print("Sammy" * 9)

Output

SammySammySammySammySammySammySammySammySammy

With string replication, we can repeat the single string value the amount of times equivalent to the integer value.

Storing Strings in Variables

Variables are symbols that you can use to store data in a program. You can think of them as an empty box that you fill with some data or value. Strings are data, so we can use them to fill up a variable. Declaring strings as variables can make it easier for us to work with strings throughout our Python programs.

To store a string inside a variable, we simply need to assign a variable to a string. In this case let’s declare my_str as our variable:

my_str = "Sammy likes declaring strings."

Now that we have the variable my_str set to that particular string, we can print the variable like so:

print(my_str)

And we will receive the following output:

Output

Sammy likes declaring strings.

By using variables to stand in for strings, we do not have to retype a string each time we want to use it, making it simpler for us to work with and manipulate strings within our programs.

Conclusion

This tutorial went over the basics of working with the string data type in the Python 3 programming language. Creating and printing strings, concatenating and replicating strings, and storing strings in variables will provide you with the fundamentals to use strings in your Python 3 programs.

Continue learning more about strings by taking a look at the following tutorials:

Tutorial Series

A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Made up of Unicode, strings are immutable sequences, meaning they are unchanging.
Because text is such a common form of data that we use in everyday life, the string data type is a very important building block of programming.
This tutorial series will go over several of the major ways to work with and manipulate strings in Python 3.

This Python tutorial will go over the basics of working with strings, including how to create and print strings, concatenate and replicate strings, and store strings in variables.

September 15, 2016

In this tutorial, we’ll go over some of the ways we can work with Python strings to make sure that all output text is formatted correctly. Quotes, apostrophes, multiple lines, escape characters, and raw strings will be covered.

September 20, 2016

Python has several built-in functions associated with the string data type. These functions let us easily modify and manipulate strings. We can think of functions as being actions that we perform on elements of our code. Built-in functions are those that are defined in the Python...

September 28, 2016

The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. Because a string is a sequence, it can be accessed in the same ways that other sequence-based data types are,...

Python is an extremely readable and versatile programming language. With a name inspired by the British comedy group Monty Python, it was an important foundational goal of the Python development team to make the language fun to use. Written in a relatively straightforward style with immediate feedback on errors, Python has a lot to offer as a programming language.

July 19, 2016

Python is an extremely readable and versatile programming language. While Python 2.7 and Python 3 share many similar capabilities, they should not be thought of as entirely interchangeable. This article will take you through the key differences to consider when choosing on whether to work in Python 2 or Python 3 for your development projects.

September 1, 2016

This tutorial will get you up and running with a local Python 3 programming environment in Ubuntu 16.04. Python is a versatile programming language that can be used for many different projects. First published in 1991 with a name inspired by the British comedy group Monty Python, the development team wanted to make Python a language that was fun to use.

November 22, 2016

This tutorial will get you up and running with a Python 3 programming environment on either an Ubuntu 16.04 or Debian 8 server. You'll be guided through installing Python 3 on a Linux server and setting up a programming environment. This tutorial will explicitly cover the installation procedures for Ubuntu 16.04 and Debian 8, but the general principles apply to any other distribution of Debian Linux.

September 14, 2016

This tutorial will walk you through writing a “Hello, World” program in Python 3. Serving as a simple and complete first program for beginners, as well as a good program to test systems and programming environments, “Hello, World!” illustrates the basic syntax of programming languages. The “Hello, World!” program is a classic tradition in computer programming. print("Hello, World!")

June 20, 2017

This tutorial will go over how to work with the Python interactive console and leverage it as a programming tool. Providing access to all of Python’s built-in functions and any installed modules, command history, and auto-completion, the interactive console offers the opportunity to explore Python and the ability to paste code into programming files when you are ready.

This Python tutorial will go over the basics of working with strings, including how to create and print strings, concatenate and replicate strings, and store strings in variables.

September 15, 2016

In this tutorial, we’ll go over some of the ways we can work with Python strings to make sure that all output text is formatted correctly. Quotes, apostrophes, multiple lines, escape characters, and raw strings will be covered.

September 20, 2016

Python has several built-in functions associated with the string data type. These functions let us easily modify and manipulate strings. We can think of functions as being actions that we perform on elements of our code. Built-in functions are those that are defined in the Python...

September 28, 2016

The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. Because a string is a sequence, it can be accessed in the same ways that other sequence-based data types are,...

This Python 3 tutorial will guide you through converting data types including numbers, strings, tuples and lists, as well as provide examples to help familiarize yourself with different use cases.

October 12, 2016

This tutorial will cover some variable basics and how to best use them within the Python 3 programs you create. We'll go through naming rules and conventions, reassigning variables, multiple assignment, and making local and global variables.

This tutorial will guide you through some of the common uses of string formatters in Python, which can help make your code and program more readable and user friendly.

October 26, 2016

This tutorial will go over operators that can be used with number data types in Python.

November 3, 2016

This tutorial will go through a few of the built-in functions that can be used with numeric data types in Python 3. Becoming familiar with these methods can give you more flexibility when programming. We’ll go over the following functions: abs() for absolute value, divmod() to find a quotient and remainder simultaneously, pow() to raise a number to a certain power, round() to round a number to a certain decimal point, sum() to calculate the sum of the items in an iterable data type.

November 17, 2016

The Boolean data type can be one of two values, either True or False. We use Booleans in programming to make comparisons and to control the flow of the program. Booleans represent the truth values that are associated with the logic branch of mathematics, which...

October 28, 2016

This tutorial will go through some of the ways that we can work with lists in Python. Lists are great to use when you want to work with many related values. They enable you to keep data together that belongs together, condense your code, and perform the same methods and operations on multiple values at once. When thinking about Python lists and other data structures that are types of collections, it is useful to consider all the different collections you have on your computer.

November 10, 2016

In this tutorial, we’ll go through the built-in methods that you can use to work with the list data structure in Python. We’ll go through adding items to and removing items from lists, extending lists, reversing and sorting lists, and more.

January 11, 2017

List comprehensions offer a succinct way to create lists based on existing lists. When using list comprehensions, lists can be built by leveraging any...

January 18, 2017

A tuple is a data structure that is an immutable, or unchangeable, ordered sequence of elements. Because tuples are immutable, their values cannot be modified. Tuples are used for grouping data. Each element or value that is inside of a tuple is called an item.

January 23, 2017

The dictionary is Python’s built-in mapping type. Dictionaries map keys to values and key-value pairs provide a useful way to store data in Python. Typically used to hold data that are related, such as the information contained in an ID or a user profile,...

January 31, 2017

This tutorial will walk you through installing modules, importing modules, and aliasing modules. Modules are Python .py files that consist of Python code. They can create function definitions and statements that you can reference in other Python .py files or via the Python command line interpreter. In Python, modules are accessed by using the import statement, which tells the current program to bring in the definitions and statements of the other relevant file(s) for its own use.

A while loop implements the repeated execution of code based on a given Boolean condition. The code that is in a *while* block will execute as long as the *while* statement evaluates to True.

January 10, 2017

Using loops in computer programming allow us to automate and repeat similar tasks multiple times. In this tutorial, we’ll be covering Python’s for loop. A for loop implements the repeated execution of code based on a loop counter or loop variable. This means that for loops are used...

January 5, 2017

The break, continue, and pass statements in Python will allow you to use for loops and while loops more effectively in your code.

February 27, 2017

A function is a block of instructions that performs an action and, once defined, can be reused. Functions make code more modular, allowing you to use the same code over and over again. Python has a number of built-in functions that you may be familiar with,...

In this tutorial, we’ll go through creating classes, instantiating objects, initializing attributes with the constructor method, and working with more than one object of the same class.

March 24, 2017

Object-oriented programming allows for variables to be used at the class level or...

March 30, 2017

This tutorial will go through some of the major aspects of inheritance in Python, including how parent classes and child classes work, how to override methods and attributes, how to use the super() function, and how to make use of multiple inheritance.

Polymorphism allows for flexibility and loose coupling so that code can be extended and easily maintained over time.
This tutorial will go through applying polymorphism to classes in Python.

April 25, 2017

In software development, debugging is the process of looking for and then resolving issues that prevent the computer software from running correctly.
The Python debugger `pdb` provides a debugging environment for Python programs. It supports setting conditional breakpoints, stepping through the source code one line at a time, stack inspection, and more.

April 26, 2017

Debugging is a part of the software development process where programmers look for and then resolve issues that prevent the software from running correctly. A useful and quick tool for debugging is the Python code module...

May 2, 2017

The logging module is part of the standard Python library and provides tracking for events that occur while software runs. You can add logging calls to your code to indicate what events have happened. The logging module allows for both diagnostic logging that records...

May 12, 2017

This tutorial will guide you through best practices and considerations to make when migrating code from Python 2 to Python 3, and whether you should maintain code that is compatible with both versions.