Strings in Python


Let’s look at strings (str) in Python. The string is one of the scalar types in Python. The standard scalar types in Python are: None, str, bytes, float, bool and int. Here are some code examples that I ran in Jupyter Notebook with Anaconda Navigator.

'string with single quote'
"double quote string works also"
'''a string on 
two lines'''
a = "this is a string"
b = a.replace("string", "longer string")

num = 42    # a number
x = 'Bart'  # a string
'My name is {} and my number is {}'.format(x, num)   # x first and num next

# For printing you should really use the print() function. 
# It does not have the Out[] at the left and prints the contents of the variable
print('hello world')
print('\n')                 # \n is the newline character

print('My name is {a} and my number is {b}. Thanks, {a}.'.format(a=x, b=77))


Indexing Strings

# indexing starts at zero.
greet = 'hello'  
greet[0]   # h
print(greet[1])
print(greet[0:2])
print(greet[:2])
print('h' + greet[1:])
e
he
he
hello

Backslash Character

The backslash character \ is an escape character, meaning that it is used to specify special characters like newline \n or Unicode characters. To write a string literal with backslashes, you need to escape them:

s = "12\\34"
print(s)
12\34

Formatting

In the following code, the .2f says to format it as a floating point number with two decimal places. It will round up in this case. The 1:s means to format it as a string. The 2.d means to format it as an exact integer.

template = "{0:.2f} and {1:s} and finally {2:d}"
template.format(73.297, 'Bob', 127)
'73.30 and Bob and finally 127'

Leave a Reply