How To Use Python Strings

How To Use Python Strings

The String data type is one of the most common you’ll likely use in Python. Strings are used to represent text, and text is something that is quite useful to work on and manipulate in a Python application. Python strings are immutable, meaning they can not be changed in place once created. You can manipulate a string, and then store its contents in a new variable, but the original string will remain intact. In this tutorial, we’ll take a look at some different concepts with regards to Strings in Python. We’ll look at formatting strings, learn about what are known as “F Strings”, understand what a docstring is, learn how to use slashes and backslashes, make use of variables in Python strings, and see how to look for substrings within strings. Let’s get started.


Creating A String

A String in Python is one or more characters. Anything inside of either single quotes ' ', or double quotes " ", is considered a string. Even a string with nothing in it (an empty set of single or double quotes) is still a string. Here are a few examples of strings in Python:

Why can you use single or double quotes? The ability to use single or double quotes allows for two things. First, you can choose the format that works best for your preference. Second, it allows you so put quoted strings inside the string. For example:


Using str() To Create A String

The str() function allows you to turn a different data type into a string.

<class 'str'>

<class 'str'>

<class 'str'>

<class 'str'>

<class 'str'>

Concatenate Strings Using +

The + operator allows you to add string literals as well as string variables.

Check out this Python String!

Check out this Python String!!

You don’t even have to use the + operator if you’re feeling particularly lazy when working with string literals (not variables). If you assign several strings one after the other to a variable, Python will automatically concatenate for you with no use of the + operator.

This is a string added together

Spaces are not automatically added for you when concatenating strings in Python, so you need to account for that. The print() function does add a space between each argument as well as a newline at the end.


Multiplying Strings

You can easily duplicate strings with the * operator in Python.

two two 

three three three

five five five five five

Python String Format

Before we look at F Strings, let’s see how the .format() function works in Python. This is important because any code prior to Python 3.6 made use of this function exclusively when working with Strings. Here is an example of using the .format() function with a Python String having one variable.

Python is the best programming language

The curly braces {} act as a placeholder for the variable. When the program runs, the contents of the string variable are put in the place of the curly braces. You can use multiple variables in one shot with the .format() function. The curly braces will be filled with the variables in the order provided.

This is the 1st variable, 2nd variable, and 3rd variable

Python F String

Starting with Python 3.6, programmers can now use what is knowns as f-strings. This new feature allows you to omit the use of the .format() function and introduces a type of string interpolation. Curly braces {} are still used as the placeholder for variables, but all you need to do now is precede the string with a lowercase f to denote an f-string. Then, you fill in the variable names inside of the curly braces. Here is the code example just above, rewritten to make use of f-strings:

This is the 1st variable, 2nd variable, and 3rd variable

So whether using the older .format() function, or f-strings, we now know how to use variables in Python Strings.


Backslash (Escape) In Python Strings

Some characters are not valid by themselves in a string. A workaround for this scenario is to use an escape character to tell Python to allow the special character. A backslash \ followed by the character to include in the string is what is known as an escape character. So when would you use an escape character? Well, we saw how we could mix and match the use of single and double quotes to define strings in Python. If you would rather use just one or the other, the escape character can help you with that. Here are some examples:

Single quotes using the escape character

Double quotes using the escape character

To Print This Use This Escape Character
Double Quote \"
Tab \t
Single Quote \’
Backslash \\
Line Break \n

What if an escape character is actually part of the string?. The fix for this scenario is to use what is known as a Raw String. A raw string in Python ignores all escape characters and prints the string “as is”. Here is an example of a raw string in Python:

Some common escape characters are \', \", \t, \n, and \\

Triple Quoted Strings

We saw how to use single and double quotes with strings in Python. You can also use triple quotes! Triple quotes are used for a few things in Python. The first is to print out a string and make use of multiple lines in the string. Another use of triple quotes is to be able to mix and match single and double quotes in a string with no ill effects. The last application of triple quotes is to create what is known as a Python Docstring. A Docstring is a way to describe the behavior of what a function in Python does. Here are some triple quote string examples in Python:

Printing Out Multiple Lines

This string

has some line breaks

in it

Single and Double Quotes inside Triple Quotes

I don't like your overused "Air Quotes"

Describing Function Behavior Using A Docstring


Check If A String Contains A String

Many times it is helpful to know if a string contains a particular string within it. In other words, it is common to look for a substring within a string. There are a few ways to check to see if a certain string contains a given substring in Python. Let’s see a few examples.

The in operator

False

True

The not in operator

True

False

The in and not in operators can be used with strings to see if they do, or do not contain a specific substring. The use of in or not in will evaluate to a Boolean True or False.

The .find() function

-1

3

You can also use the .find() method to see if a string contains a specific value. This approach does not evaluate to True or False, but rather returns an integer value. If the substring is not found, -1 is the result. If the value is found, the result is the integer value of the beginning of the substring.


Python String Case Methods

Python has several methods the deal with the case of a string. These include lower(), swapcase(), title(), upper(), islower(), istitle(), and isupper().

.lower() Returns a copy of the string converted to lowercase.

cool fun string

note: You may also use the .casefold() function for this as a more powerful version of .lower() as it remove all case distinctions in a string including special characters making it suitable for caseless comparisons.

.swapcase() Converts uppercase characters to lowercase and lowercase characters to uppercase.

cOOL fUN sTRING

.title() Returns a version of the string where each word is title cased. In other words, words start with uppercase characters and all remaining cased characters have lowercase.

Cool Fun String

.upper() Returns a copy of the string converted to uppercase.

COOL FUN STRING

.islower() Returns True if the string is a lowercase string, False otherwise. A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

False

.istitle() Returns True if the string is a title-cased string, False otherwise. In a title-cased string, upper and title-case characters may only follow uncased characters and lowercase characters only cased ones.

True

.isupper() Returns True if the string is an uppercase string, False otherwise. A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

False

.capitalize() Returns a capitalized version of the string. This function makes the first character have upper case and the rest lower case.

Cool fun string

How To Slice Strings

Strings in Python are a sequence of characters. Each character lives at an index. The index is like the position that the character occupies. To show this, we can use the .index() method to see where in the string a certain character exists.

.index() Returns the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.

16

Note that this is case sensitive. Look at what happens if a capital letter is used instead.

Traceback (most recent call last):
  File "C:/python/justhacking/strings.py", line 3, in <module>
    print(the_str.index('F'))
ValueError: substring not found

Consider this code:

5

The value of 5 is returned. How does this work? It may help to see a visualization. If you are familiar with lists in Python, then you know the concept of an item in a list having an index. You can almost think of strings like a list as well. Each character in a string has a given index. Here is the visual representation of this example we just looked at.

python string index position

Knowing this, we can now use the standard slice notation on strings to access specific characters or a range of characters.

S

i

y

String

Str

ify

If you specify an index, you get the character at that position in the string. If you specify a range from one index to another, the starting index is included however the ending index is not. The substring you get from the_str[0:6] will include everything from the_str[0] to the_str[5].

  • [:] Grabs the entire string from beginning to end
  • [start:] Grabs the string at the start offset to the end
  • [:end] Grabs all characters from the start to end offset -1
  • [start:end] Begins at the start offset to the end offset -1
  • [start:end:step] Begins at the start offset to the end offset -1 in step increments

Checking String Length Using len()

To check the length of a string in Python you can use the built-in len() function.

26

The len() function also counts the number of items in an object. As we just saw above, if we are working with a string the len() function counts the number of characters in the string.


Substring Substitution Using replace()

The replace() function can be used to look for and replace certain characters or words in a string. Since strings are immutable, this function does not actually modify the original string, it makes the replacements and returns a new string.

Out with the old, in with the old

Hmm, that’s not quite right. By default the .replace() will look for all occurrences of the characters to replace, and will replace them. There is also an optional third parameter which specifies how many to replace. We can fix the example above with that third parameter.

Out with the old, in with the new

Splitting And Joining Strings

If a string has several words, you can split up the string into a list based on whitespace characters. Let’s see how the .split() method works.

.split() Returns a list of the words in the string, using whitespace characters as the default delimiter.

['Just', 'A', 'String']

To turn a list of words back into a string, you have access to the .join() function.

.join() Concatenate any number of strings. The string whose method is called is inserted in between each given string. The result is returned as a new string.

Just A String

The syntax might be a little confusing. What you are doing is calling the .join() method on the string representation of the separator that you would like to use. So you could join a list of words on the happy face if you like.

Just πŸ˜ƒ A πŸ˜ƒ String

Counting Character or Substring Occurrences

Sometimes, you might want to count the number of times a substring occurs within a given string. In Python, you can use the .count() function to do this. You can count the number of times a substring appears, or you can count the number of times a single character appears.

.count() Returns the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

1

3

2

Startswith and Endswith

There are two methods to check if a string starts with or ends with a specific character or substring. These are the .startswith() and .endswith() methods.

.startswith() Returns True if the string starts with the specified prefix, False otherwise.

True

False

.endswith() Returns True if the string ends with the specified suffix, False otherwise.

True

False

Adding Tabs or Newlines To Strings

Sometimes it helps to add either tabs, newlines, or some other form of white space to help format the output of a program to make it easier for the end-user to read. Let’s see a few examples of how to do this.

Python String 	Python String 		Python String

Python String
 	Python String
 		Python String

Tabs To Spaces With expandtabs()

Python has an .expandtabs() function which returns a copy of the string where all tab characters are expanded using spaces. If a tab size is not given, a tab size of 8 characters is used. The below example removes the leading and trailing tab characters and replaces them with 4 spaces each.

    Strawberry Blueberry Jam    

Using strip() rstrip() and lstrip()

It’s quite common to have a need to remove leading or trailing whitespace characters in a string. These include spaces, tabs, and newlines. To clean up string you can use either .strip(), .rstrip(), or .lstrip(). These are pretty self explanatory and do exactly what you think.

.strip() Removes whitespace characters from both sides of the string.
.rstrip() Removes whitespace characters from the right side of the string.
.lstrip() Removes whitespace characters from the left side of the string.

If you have specific characters you want to strip, you can pass that as an argument to the function.

 This is a nice string

Aligning Strings

Python has a few alignment functions you can use to neatly format how a string is displayed. The function to handle aligning strings are the .center(), .ljust(), and .rjust() functions. The way these functions work is to pass them a number which specifies how wide the “box” is that will hold the string to be justified. For example, if you pass the number 34 to the .center() function, it means that you want a particular string to be centered in a layout area that is 34 characters wide. Let’s see how this works.

     Strawberry Blueberry Jam     
Strawberry Blueberry Jam          
          Strawberry Blueberry Jam

You can use a custom character as the padding character as well. This approach gives an even clearer visual representation of the alignment happening. We’ll use a few emoji characters as the padding character here.

πŸ“πŸ“πŸ“πŸ“πŸ“Strawberry Blueberry JamπŸ“πŸ“πŸ“πŸ“πŸ“
Strawberry Blueberry Jam🌱🌱🌱🌱🌱🌱🌱🌱🌱🌱
🌱🌱🌱🌱🌱🌱🌱🌱🌱🌱Strawberry Blueberry Jam

Learn More About Python Strings


How To Use Python Strings Summary

Processing text information is very common in almost all computer programs and Python has many built-in functions to help make working with strings easier. We learned about how to create strings, slice strings, count the length of strings, concatenate strings, multiply strings, format strings, work with f-strings, handle the case of strings, use escape characters in strings, searched for substrings in strings, split and join strings, and much more.