left-icon

Python Succinctly®
by Jason Cannon

Previous
Chapter

of
A
A
A

CHAPTER 1

Variables and Strings

Variables and Strings


Variables

Put quite simply, variables are named storage locations. They can also be described as name-value pairs. It is possible for you to assign values to a variable, and then recall those values by the variable name. To assign a value to a variable, use the equal sign. The pattern is variable_name = value.

In the following example, the value asparagus is assigned to the variable called vegetable.

Code Listing 14

vegetable = 'asparagus'

It is possible to change the value of a variable simply by reassigning it. View the following example to see how to reset the value of the vegetable variable to the value onion.

Code Listing 15

vegetable = 'onion'

Note that there is nothing significant about the variable named vegetable in this example. We could have just as easily used the words food, crop, produce, or almost any other variable name that we could possibly think of. When choosing a variable name, you want to select something that will ultimately represent the data the variable will hold. While you may know what a variable named v represents today, it may not be so fresh in your mind when you return to the code a few months from now. However, if you come across a variable named vegetable, chances are you’ll have a greater understanding of what data it might hold.

Keep in mind that variable names are always case sensitive. So, variables Vegetable and vegetable will be two distinct and separate variables. By convention, variables are usually named with all lower case letters, but this is by no means a requirement. While variable names can contain numbers in the body of the name, they must always start with a letter. Another rule to remember is that you cannot use a hyphen (-), plus sign (+), or other various symbols in variable names. You can however use the underscore (_) character.

The following are some examples of valid variable names.

Code Listing 16

last3letters = 'XYZ'

last_three_letters = 'XYZ'

lastThreeLetters = 'XYZ'

Strings

A string is utilized to represent text. In the previous examples strings were represented by the text asparagus, onion, and XYZ. In Python strings are always surrounded by quotes. Let's revisit the first example in this chapter when we created a variable named vegetable and assigned it the string asparagus.

Code Listing 17

vegetable = 'asparagus'

Strings can also be encapsulated by the use of double quotes.

Code Listing 18

vegetable = "asparagus"

Using Quotes within Strings

It is important to remember that Python requires matching quotation marks for all strings that you enter. Whenever you begin a string definition by using a double quotation mark, Python will interpret the next double quotation mark you enter as the end of that string. The same will be true when using single quotation marks. If you begin a string with a single quotation mark, the next single quotation mark will represent the end of that particular string.

In instances where you want to include double quotations in a string, make sure to place them inside single quotation marks as in the following example.

Code Listing 19

sentence = 'He said, "That asparagus tastes great!"'

If you want to incorporate single quotes in a string, make sure to enclose the entire string in double quotation marks.

Code Listing 20

sentence = "That's some great tasting asparagus!"

What if you were looking to use both single and double quotes in the same string? At this point you would need to escape the offending quotation character by prepending it with a backslash (\). The following code listing demonstrates how to escape the following string when making use of double and single quotes.

He said, "That's some great tasting asparagus!"

Code Listing 21

sentence_in_double = "He said, \"That's some great tasting asparagus!\""

sentence_in_single = 'He said, "That\'s some great tasting asparagus!"'

Indexing

It is important to note that each character in a string will be assigned an index. All string indices are zero based, which means that the first character in any string will have an index of 0, the second character will have an index of 1, and so on.

Code Listing 22

String:   a s p a r a g u s

 Index:   0 1 2 3 4 5 6 7 8

In order to access the character at a given index, append [N] to a string where N is the index number. The following example creates a variable which is named a and assigns it the character in position 0 of the string asparagus. Similarly, a variable of r is created using the character from position 4 of asparagus.

Code Listing 23

a = 'asparagus'[0]

r = 'asparagus'[4]

Since variables are quite simply names that represent their values, the [N] syntax will also work with any other variable. In the following example, first_char will be assigned the value a.

Code Listing 24

vegetable = 'asparagus'

first_char = vegetable[0]

Built-in Functions

A function is an action-performing section of reusable code. A function will always have a name and will be called, or executed, by that name. Optionally, functions are able to accept arguments as well as return data.

The print() Function

The print() function is just one of Python’s many built-in functions. Any time a value is provided as an argument to the print() function, it will display that value to the screen. You can supply literal values like "cat" or 7 to the print statement or opt to pass in variables.

Code Listing 25

vegetable = 'asparagus'

print(vegetable)

print('onion')

Output:

Code Listing 26

asparagus

onion

The len() Function

Another useful built-in Python function is the len() function. When a string is passed as an argument to the len() function, it returns the length of that string. Put more simply, len() returns the number of characters in a string.

In the following example the value asparagus is assigned to the variable named vegetable. From there we assign the result of len(vegetable) to the vegetable_len variable. Finally we display that value to the screen by making use of the print(vegetable_len) function.

Code Listing 27

vegetable = 'asparagus'

vegetable_len = len(vegetable)

print(vegetable_len)

Output:

Code Listing 28

9

You can also skip the intermediary step of assigning it to a variable and pass the len() function directly to the print() function. This works because len(vegetable) is evaluated first, and from there its value is used by the print() function.

Code Listing 29

vegetable = 'asparagus'

print(len(vegetable))

Output:

Code Listing 30

9

If you’re so inclined you can even skip using variables all together.

Code Listing 31

print(len('asparagus'))

Output:

Code Listing 32

9

String Methods

Without delving too deeply into the subject of object-oriented programming (OOP), it can be helpful to understand a few key concepts before continuing. One of the first things you should know is that absolutely everything in Python is an object. In turn, every object has a type. Though you are currently learning about the string data type, we will cover various other types throughout the course of this book.

For now let's focus our attention on strings. For example, 'asparagus' is an object with a type of "str," which is short for string. Simply put, 'asparagus' is a string object. If we assign the value asparagus to the variable vegetable using vegetable = 'asparagus', then vegetable is also a string object. Keep in mind that variables are names that represent their values.

As mentioned previously, a function is a section of reusable code that will perform an action. Up to this point you have been using built-in functions like print() and len(). Objects also have functions, but they are not usually described as such. In fact, they are called methods. Methods are merely functions that are run against an object. In order to call a method on an object, simply follow the object with a period, then the method name, and finally a set of parentheses. Make sure to enclose any parameters within the parentheses.

The lower() String Method

The lower() method of a string object will return a copy of the string in all lowercase letters.

Code Listing 33

vegetable = 'Asparagus'

print(vegetable.lower())

Output:

Code Listing 34

asparagus

The upper() String Method

Conversely, the upper() string method will return a copy of the string in all uppercase letters.

Code Listing 35

vegetable = 'Asparagus'

print(vegetable.upper())

Output:

Code Listing 36

ASPARAGUS

String Concatenation

To concatenate, or combine two strings, use the plus sign. A simple way of thinking about this is imagining that you were adding strings together. You can concatenate multiple strings by using additional plus signs and strings. In the following example take note of how spaces are included in the strings. String concatenation only combines the strings as they are.

Code Listing 37

print('Python ' + is  ' + 'fun.')

print('Python' + ' is' + ' Python.')

Output:

Code Listing 38

Python is fun.

Python is fun.

If you fail to include extra spaces, it will be reflected in your output, as in the following example.

Code Listing 39

print('Python' + 'is' + 'fun.')

Output:

Code Listing 40

Pythonisfun.

The next example demonstrates string concatenation using variables combined with the space character literal.

Code Listing 41

first = 'Python'

second = 'is'

third = 'fun'

sentence = first + ' ' + second + ' ' + third + '.'

print(sentence)

Output:

Code Listing 42

Python is fun.

Repeating Strings

It is important to note that whenever you are working with strings, the asterisk is the repetition operator. The pattern is 'string' * number_of_times_to_repeat. For example, if you want to display a hyphen twelve times, use '-' * 12.

Code Listing 43

print('-' * 12)

Output:

Code Listing 44

------------

Keep in mind that you don't have to use repetition with just single character strings.

Code Listing 45

good_times = 'fun ' * 3

print(good_times)

Output:

Code Listing 46

fun fun fun

The str() Function

In a later chapter of this book you will learn about numeric data types. For now though, just know that unlike strings, numbers will not be enclosed within quotation marks. To concatenate a string with a number, you must first convert the number to a string with the built-in str() function. The str() function will turn non-strings, such as numbers, into strings.

Code Listing 47

version = 3

print('Python ' + str(version) + ' is fun.')

Output:

Code Listing 48

Python 3 is fun.

The following example shows you what will happen if a number is not converted to a string before you attempt concatenation.

Code Listing 49

version = 3

print('Python ' + version + ' is fun.')

Output:

Code Listing 50

  File "string_example.py", line 2, in <module>

    print('Python ' + version + ' is fun.')

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

Formatting Strings

Calling the format() method on a string to produce the format you desire is an alternative to directly concatenating strings. Do this by creating placeholders, also known as format fields, by using curly braces in the string and passing in values for those fields to format().

By default the first pair of curly braces will always be replaced by the first value passed to format(). The second pair of curly braces will be replaced by the second value passed to format(), and so on. The following example illustrates this.

Code Listing 51

print('Python {} fun.'.format('is'))

print('{} {} {}'.format('Python', 'is', 'fun.'))

Output:

Code Listing 52

Python is fun.

Python is fun.

Be sure to note that when you pass multiple objects to a function or method you must separate them using a comma.

Also, you can implicitly state which positional parameter will be used for a format field simply by providing a number inside the braces. {0} will be replaced with the first item passed to format(), {1} will be replaced by the second item passed in, and so on.

Code Listing 53

print('Python {0} {1} and {1} {0} awesome!'.format('is', 'fun'))

Output:

Code Listing 54

Python is fun and fun is awesome!

The following formatting example makes use of variables.

Code Listing 55

first = 'Python'

second = 'is'

third = 'fun'

print('{} {} {}.'.format(first, second, third))

Output:

Code Listing 56

Python is fun.

With what we’ve learned we can now rewrite our previous example combining strings and numbers by using the format() method. This completely eliminates the need to use the str() function.

Code Listing 57

version = 3

print('Python {} is fun.'.format(version))

Output:

Code Listing 58

Python 3 is fun.

When needed, you can also supply a format specification. Format specifications will be confined within the curly braces. To create a field with a minimum character width, simply supply a number after the colon. The format field {0:9} will translate to "use the first value provided to format() and make it at least nine characters wide." The format field {1:8} means "use the second value provided to format() and make it at least eight characters wide." This method can be useful in many instances, including the creation of tables.

Code Listing 59

print('{0:9} | {1:8}'.format('Vegetable', 'Quantity'))

print('{0:9} | {1:8}'.format('Asparagus', 3))

print('{0:9} | {1:8}'.format('Onions', 10))

Output:

Code Listing 60

Vegetable | Quantity

Asparagus |        3

Onions    |       10

In order to control the alignment, always use < for left, ^ for center, and > for right. If no particular alignment is specified, left alignment will always be assumed. Making use of our previous example, let's try to left align the numbers.

Code Listing 61

print('{0:9} | {1:<8}'.format('Vegetable', 'Quantity'))

print('{0:9} | {1:<8}'.format('Asparagus', 3))

print('{0:9} | {1:<8}'.format('Onions', 10))

Output:

Code Listing 62

Vegetable | Quantity

Asparagus | 3

Onions    | 10

If needed, you can also specify a data type. The most common instance of this is to use f which will represent a float. Floats, or floating point numbers, will be addressed in depth in the following chapter. Also, you can stipulate the number of decimal places by using .Nf where N is the number of decimal places. A common currency format would be .2f which specifies two decimal places. The following is an idea of what our table might look like once we’ve taken a few nibbles out of our asparagus.

Code Listing 63

print('{0:8} | {1:<8}'.format('Vegetable', 'Quantity'))

print('{0:9} | {1:<8.2f}'.format('Asparagus', 2.33333))

print('{0:9} | {1:<8.2f}'.format('Onions', 10))

Output:

Code Listing 64

Vegetable | Quantity

Asparagus | 2.33

Onions    | 10.00

Getting User Input

To accept standard input use the built-in function input(). By default, standard input originates from a person typing at a keyboard. This will allow you to prompt the user directly for their input. In more complex cases standard input can come from other sources. For example, you are able to send the output from one command as the standard input to another command just by using pipes. (For more info on this topic refer to Linux for Beginners at http://www.linuxtrainingacademy.com/linux.)

Keep in mind that you can pass in a prompt to display to the input() function.

Code Listing 65

vegetable = input('Enter a name of a vegetable: ')

print('{} is a lovely vegetable.'.format(vegetable))

Output:

Code Listing 66

Name a vegetable: asparagus

asparagus is a lovely vegetable.

Review

Variables are names that store values.

Variable names may contain letters, numbers, and underscores, but must always begin using a letter.

Values can be assigned to variables using the variable_name = value pattern.

Strings are always surrounded by single or double quotation marks.

An index is assigned to each character in a string.

A function is an action performing reusable code.

Built-in functions:

  • print(): Displays values.
  • len(): Returns the length of an item.
  • str(): Returns a string object.
  • input(): Reads a string.

Absolutely everything in Python is an object.

It is possible for objects to have methods.

Methods are functions that will operate on an object.

String methods:

  • upper(): Returns a copy of the string in uppercase.
  • lower(): Returns a copy of the string in lowercase.
  • format(): Returns a formatted version of the string.

Exercises

Animal, Vegetable, Mineral

Try to write a Python program that makes use of three variables. The variables you will use in your program will be animal, vegetable, and mineral. Make sure to assign a string value to each one of these independent variables. Your program should be able to display "Here is an animal, a vegetable, and a mineral." From there, display the value for animal, followed by vegetable, and then finally mineral. Each one of the values should be printed on their own individual line. The output should be four lines in total.

Sample Output:

Code Listing 67

Here is an animal, a vegetable, and a mineral.

deer

spinach

aluminum

I strongly encourage you to successfully create a Python program that is capable of producing the output in the previous code listing before continuing. For the remainder of this book the solutions to the exercises will follow the exercise explanation and sample output. If you want to attempt the exercise on your own—and I encourage you to do so—stop reading now.

Solution

Code Listing 68

animal = 'deer'

vegetable = 'spinach'

mineral = 'aluminum'

print('Here is an animal, a vegetable, and a mineral.')

print(animal)

print(vegetable)

print(mineral)

Copy Cat

Try writing a Python program that directly prompts the user for input, and then simply repeats the information the user entered.

Sample output:

Code Listing 69

Please type something and press enter: Hello world!

You entered:

Hello world!

The following is one possible solution. It may be that your program looks slightly different, but ideally it should be fairly similar. One example of a possible difference is that you may find you have used a different variable name. If you successfully reproduced the previous output, keep at it! You're doing great!

Code Listing 70

user_input = input('Please type something and press enter: ')

print('You entered:')

print(user_input)

Pig Speak

Try writing a Python program that will prompt for input and then display a pig "saying" whatever text was provided by the user. Place the input you receive from the user inside a speech bubble. Expand or contract the speech bubble in order to make it fit around the input provided.

Sample output:

Code Listing 71

              ______________________

            < Feed me and I'll oink! >

              ----------------------

            /

     ^..^  /

~(  ( oo )

  ,,  ,,

Solution

Code Listing 72

text = input('What would you like the pig to say? ')

text_length = len(text)

print('              {}'.format('_' * text_length))

print('            < {} >'.format(text))

print('              {}'.format('-' * text_length))

print('            /')

print('     ^..^  /')

print('~(  ( oo )')

print('  ,,  ,,')

Output:

Code Listing 73

What would you like the pig to say? Oink

              ____

            < Oink >

              ----

            /

     ^..^  /

~(  ( oo )

  ,,  ,,

Resources

Common String Operations: https://docs.python.org/3/library/string.html

input() documentation: https://docs.python.org/3/library/functions.html?highlight=input#input

len() documentation: https://docs.python.org/3/library/functions.html?highlight=input#len

print() documentation: https://docs.python.org/3/library/functions.html?highlight=input#print

str() documentation: https://docs.python.org/3/library/functions.html?highlight=input#func-str

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.