Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lecture 01: Python primer

University of Lausanne

Course: Deep Learning for Solving and Estimating Dynamic Models in Economics and Finance
Script reference: Front matter and Appendix~E — string handling, f-strings, printing
Notebook role: primer (pre-course self-study; skip if you write Python every day)
Author: Simon Scheidegger

Python Basics 4: Basics of Strings

Python str’s (“str” stands for “string”) are used to represent text. Here is a string:

x = "This is a string"
x
'This is a string'

We could have also used double quotes:

x = 'This is the same string'
x
'This is the same string'

Here is the string type:

type(x)
str

You can do many things with strings. For a complete list see help(str). Here we will survey the most frequently encountered string operations.

First, you can join two strings together:

y = ', and another string.'
y
', and another string.'
z = x + y
z
'This is the same string, and another string.'

Here is how you can center a string:

z.center(80) # 80 is the total number of characters in a row:
' This is the same string, and another string. '

You can also multiply a string with a number to repeat it many times:

'=' * 80
'================================================================================'

You can ask how many characters are in a string:

len(z)
44

You can also make substrings using indices. These work in exactly the same way as the do for tuples and lists:

z[::-1]
'.gnirts rehtona dna ,gnirts emas eht si sihT'
z[2:10]
'is is th'
z[0]
'T'

Another useful thing is padding a string representing a number with zeros. This is particularly useful when reading many data files numbered as “001, 002, 003,” etc. Here it is:

'23'.zfill(5)
'00023'
'1'.zfill(4)
'0001'

There is also an empty string:

''
''
''.zfill(4)
'0000'
len('')
0

Now I am going to show you the most important thing you need to remember: How to turn into strings integers and floats so that you present the result of your analysis. Let’s get some numbers first:

# an integer
a = 123
# a floating point number
b = 12.908450

Let’s say that you want to put these numbers into a string so that you print them on the screen or maybe write something in a text file. Let’s keep it simple. Say that we want to write: “After my calculation I found out that a=replace with value for a and that b=replace with value for b.” Here is one way to do this - not the best one though:

x = 'After my calculation I found out that a=' + str(a) + ' and that b=' + str(b)
x
'After my calculation I found out that a=123 and that b=12.90845'

So, all we did is turn the numbers into strings (using str(number)) and the add the strings together. This is not the best way it doesn’t allow us to change the number of significant digists we present. The best way to do it is to use string formating:

x = 'After my calculation I found out that a={0:d} and that b={1:1.2f}'.format(a, b)
x
'After my calculation I found out that a=123 and that b=12.91'

Let me explain what this does. First notice the brackets: {0:d} and {1:1.2f}. The number in the bracket before the : matches an input variable in the format(a, b) function that follows. For example, the 0 of {0:d} matches the first input of format which is a. The first 1 (before the :) of {1:1.2f} matches the second input of format which is b. The characters after the : in the brackets tell Python how you would like to turn that variable into a string. The d means that you are expecting a decimal integer. The 1.2f means that you are expecting a floating point number and that you want to keep two significant digits.

Here are some other examples of formating:

'This is a={0:5d} with five characters in total padding with empty space'.format(12)
'This is a= 12 with five characters in total padding with empty space'
import math
'This is pi={0:1.30f} (thirty digits of pi)'.format(math.pi)
'This is pi=3.141592653589793115997963468544 (thirty digits of pi)'
'This is b={0:1.3e} in scientific notation with three significant digits'.format(b)
'This is b=1.291e+01 in scientific notation with three significant digits'
'This is a={0:o} in octal format.'.format(a) 
'This is a=173 in octal format.'
'And this is a={0:x} in hex format'.format(a)
'And this is a=7b in hex format'

A complete overview of the formating language is, of course, beyond the scope of this tutorial. You can find it here.

Questions

  • Rerun the code blocks above playing with the formatting brackets. Increase/decrease the number of digits. Change from decimal to float and vice versa. Add a third number ‘c=whatever you like’ in our x string above.

The print function

So far, we were only able to show things in the screen if we did something like this:

x
'After my calculation I found out that a=123 and that b=12.91'

This doesn’t work in an actual Python program, however. It only works in a Jupyter notebook. But even in Jupyter notebooks, if you wanted to show more than one thing, this doesn’t work. See this:

x
y
', and another string.'

Only y was displayed. To display x and then y, you need to use the print() function. Here it is:

print(x)
print(y)
After my calculation I found out that a=123 and that b=12.91
, and another string.

Just like formating, there are a lot of details in print(). Here, we will be only covering the very basics. Let’s start by printing some numerical variables:

a = 123
b = 98.2082
print(a)
print(b)
123
98.2082

You can also print the variables one after the other:

print(a, b)
123 98.2082

Notice that print adds an empty space between the arguments that you want to print. There is no limit to how many arguments print can have. The following also works:

print(a, b, x, y, 'and some more')
123 98.2082 After my calculation I found out that a=123 and that b=12.91 , and another string. and some more

Of course when you print numerics, you probably want to do it like this:

print('a={0:d}, b={1:1.2f}'.format(a,b))

That is, instead of just printing a and then b, you make a string with just the desired format and you print that string.

Notice that print() puts a newline each time it is called. See this:

print('This is the first line.')
print('This will appear in the second line.')

There is a way, a special character called \n which can be used to mark a newline in a string. When print() sees this character, then it adds a newline. See how it works:

print('This is the first line.\nThis will appear in the second line.')

Here, let me just print 5 new lines:

print('\n\n\n\n\n')

Characters like \n are called special characters. In this class, we will use the \t character very often to align what we print. This is called the tab character. Here is what it does:

print('A\tB\tC')

Get it? Here is why it is useful. Let’s print a table of some fake data:

print('ID\tTime (s)\tMass (kg)\t')
print('-' * 40) # Prints 40 '-'
print('{0:d}\t{1:1.2f}\t\t{2:1.2f}'.format(0, 0.01, 12.2))
print('{0:d}\t{1:1.2f}\t\t{2:1.2f}'.format(1, 0.02, 12.5))
print('{0:d}\t{1:1.2f}\t\t{2:1.2f}'.format(2, 0.05, 13.1))
print('{0:d}\t{1:1.2f}\t\t{2:1.2f}'.format(3, 0.07, 13.6))
print('{0:d}\t{1:1.2f}\t\t{2:1.2f}'.format(4, 0.08, 14.2))

Notice that I had to use two \t’s to allign the mass. It’s probably too much to try to remember all these details. We will see many more examples in the hands-on activities and you will pick up certain tricks.

Questions

Here are some data:

data = [23.0, 21.0, 23.0, 23.0, 23.84, 24.52]

Use print() and formating to present the data like this:

DATA
------
2.3e+1
2.1e+1
...

etc. Then calculate the average of the data and print it with two significant digits.

# your code here