String Functions in Python 3 - DigitalOcean
String Functions in Python 3 - DigitalOcean
Contents
Boolean Methods
Determining String
Length Subscribe Share
Conclusion
Mark as Complete
Lisa Tagliaferri
Introduction
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 programming language and are readily
available for us to use.
In this tutorial, we’ll go over several different functions that we can use to work with strings in Python 3.
ss = "Sammy Shark"
print(ss.upper())
Ouput
SAMMY SHARK
print(ss.lower())
Ouput
sammy shark
The str.upper() and str.lower() functions make it easier to evaluate and compare strings by
making case consistent throughout. That way if a user writes their name all lower case, we can still
determine whether their name is in our database by checking it against an all upper-case version, for
example.
Boolean Methods
Python has some string methods that will evaluate to a Boolean value. These methods are useful when we
are creating forms for users to fill in, for example. If we are asking for a post code we will only want to
accept a numeric string, but when we are asking for a name, we will only want to accept an alphabetic
string.
There are a number of string methods that will return Boolean values:
Method True if
number = "5"
letters = "abcdef"
print(number.isnumeric())
print(letters.isnumeric())
Output
True
False
Using the str.isnumeric() method on the string 5 returns a value of True , while using the same
method on the string abcdef returns a value of False .
Similarly, we can query whether a string’s alphabetic characters are in title case, upper case, or lower case.
Let’s create a few strings:
Now let’s try the Boolean methods that check for case:
print(movie.islower())
print(movie.isupper())
print(book.istitle())
print(book.isupper())
print(poem.istitle())
print(poem.islower())
Now we can run these small programs and see the output:
Checking whether characters are lower case, upper case, or title case, can help us to sort our data
appropriately, as well as provide us with the opportunity to standardize data we collect by checking and
then modifying strings as needed.
Boolean string methods are useful when we want to check whether something a user enters fits within
given parameters.
Output
33
We set the variable open_source equal to the string "Sammy contributes to open source." and
then we passed that variable to the len() method with len(open_source) . We then passed the
method into the print() method so that we could see the output on the screen from our program.
Keep in mind that any character bound by single or double quotation marks — including letters, numbers,
whitespace characters, and symbols — will be counted by the len() method.
The str.join() method will concatenate two strings, but in a way that passes one string through
another.
Now, let’s use the str.join() method to add whitespace to that string, which we can do like so:
" ".join(balloon)
print(" ".join(balloon))
We will see that in the new string that is returned there is added space throughout the first string:
Ouput
S a m m y h a s a b a l l o o n .
We can also use the str.join() method to return a string that is a reversal from the original string:
print("".join(reversed(balloon)))
Ouput
.noollab a sah ymmaS
We did not want to add any part of another string to the first string, so we kept the quotation marks
touching with no space in between.
The str.join() method is also useful to combine a list of strings into a new single string.
Ouput
sharks,crustaceans,plankton
If we want to add a comma and a space between string values in our new string, we can simply rewrite our
expression with a whitespace after the comma: ", ".join(["sharks", "crustaceans",
"plankton"]) .
Just as we can join strings together, we can also split strings up. To do this, we will use the str.split()
method:
print(balloon.split())
Ouput
['Sammy', 'has', 'a', 'balloon.']
The str.split() method returns a list of strings that are separated by whitespace if no other parameter
is given.
We can also use str.split() to remove certain parts of an original string. For example, let’s remove the
letter a from the string:
print(balloon.split("a"))
Ouput
['S', 'mmy h', 's ', ' b', 'lloon.']
Now the letter a has been removed and the strings have been separated where each instance of the
letter a had been, with whitespace retained.
The str.replace() method can take an original string and return an updated string with some
replacement.
Let’s say that the balloon that Sammy had is lost. Since Sammy no longer has this balloon, we will change
the substring "has" from the original string balloon to "had" in a new string:
print(balloon.replace("has","had"))
Within the parentheses, the first substring is what we want to be replaced, and the second substring is
what we are replacing that first substring with. Our output will look like this:
Ouput
Sammy had a balloon.
Using the string methods str.join() , str.split() , and str.replace() will provide you with
greater control to manipulate strings in Python.
Conclusion
This tutorial went through some of the common built-in methods for the string data type that you can use
to work with and manipulate strings in your Python programs.
You can learn more about other data types in “Understanding Data Types,” read more about strings in “An
Introduction to Working with Strings,” and learn about changing the way strings look in “How To Format
Text in Python 3.”
Tutorial Series
Show Tutorials
Show Tutorials
LEARN MORE
Related Tutorials
How To Install and Configure pgAdmin 4 in Server Mode
How To Build a Neural Network to Recognize Handwritten Digits with TensorFlow
How to Install, Run, and Connect to Jupyter Notebook on a Remote Server
How To Set Up a Jupyter Notebook with Python 3 on Debian 9
How To Set Up Django with Postgres, Nginx, and Gunicorn on Debian 9
3 Comments
Leave a comment...
0 String methods are very easy in python than Java and also it is easy to learn
Reply • Report
0 Actually there are few significant differences between Python and JS.
Reply • Report
Reply • Report
Copyright © 2018 DigitalOcean™ Inc.
Distros & One-Click Apps Terms, Privacy, & Copyright Security Report a Bug Write for DOnations Shop