Because most programs define and gather some sort of data, and then do something useful with it, it helps to classify
different types of data. The first data type we’ll look at is the string. Strings are quite simple at first glance, but you can use them in many different ways.
A string is simply a series of characters. Anything inside quotes is considered a string in Python, and you can use single or double quotes around your strings like this:
"This is a string." 'This is also a string.'
This flexibility allows you to use quotes and apostrophes within your strings:
'I told my friend, "Python is my favorite language!"' "The language 'Python' is named after Monty Python, not the snake." "One of Python's strengths is its diverse and supportive community."
Let’s explore some of the ways you can use strings.
Changing Case in a String with Methods
One of the simplest tasks you can do with strings is change the case of the words in a string. Look at the following code, and try to determine what’s happening:
name = "ada lovelace" print(name.title())
Save this file as name.py, and then run it. You should see this output:
In this example, the lowercase string “ada lovelace” is stored in the variable name. The method title() appears after the variable in the print() statement. A method is an action that Python can perform on a piece of data. The dot (.) after name in name.title() tells Python to make the title() method act on the variable name. Every method is followed by a set of parentheses, because methods often need additional information to do their work.
That information is provided inside the parentheses. The title() function doesn’t need any additional information, so its parentheses are empty.title() displays each word in titlecase, where each word begins with a capital letter. This is useful because you’ll often want to think of a name as a piece of information. For example, you might want your program to recognize the input values Ada, ADA, and ada as the same name, and display all of them as Ada.
Several other useful methods are available for dealing with case as well. For example, you can change a string to all
uppercase or all lowercase letters like this:
name = "Ada Lovelace" print(name.upper()) print(name.lower())
This will display the following:
ADA LOVELACE ada lovelace
The lower() method is particularly useful for storing data. Many times you won’t want to trust the capitalization that your users provide, so you’ll convert strings to lowercase before storing them. Then when you want to display the information, you’ll use the case that makes the most sense for each string.
This article is an excerpt from A Hands-On, Project-Based Introduction to Programming by Eric Matthes
Reproduced with permission from No Starch Press