Basics of strings

Contents

Basics of strings#

You will often have to write some text to the screen. 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 single 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(60)
'        This is the same string, and another string.        '

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

'=' * 60
'============================================================'

A string is essentially a list of characters. 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 = f'After my calculation I found out that a={a:d} and that b={b:1.2f}'
x
'After my calculation I found out that a=123 and that b=12.91'

Let me explain what this does. First notice the f at the beginning of the string, which indicates this is an f-string (formatted string literal). Inside the f-string, we have expressions in curly brackets: a:d and b:1.2f. These expressions are evaluated at runtime. The variable name before the colon (e.g., a in a:d) refers directly to the variable we want to include in the string. The characters after the colon 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:

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

  • Given variables material = "Steel" and tensile_strength = 400, create an f-string that outputs: “The tensile strength of Steel is 400 MPa.”

  • Create an f-string that displays the part number 42 with a width of 5 characters, padded with zeros on the left (e.g., “00042”).

  • Given a variable efficiency = 0.8756, create an f-string that formats it as a percentage with 2 decimal places: “87.56%”.

  • Create an f-string that displays the result of calculating the area of a circle with radius 2.5 cm, showing 3 decimal places. Include units.

  • Given variables voltage = 120.45 and uncertainty = 0.32, create an f-string that displays the measurement with its uncertainty as: “120.45 ± 0.32 V”. Make sure to format both values to 2 decimal places.

  • 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.