Basics#

Substrings#

Strings are sequence-type objects, that is, they can be regarded as lists of characters. Each character then is itself a string object.

a = 'some string'
print(a[0])
print(a[1])
print(len(a))
s
o
11

Even slicing is possible.

b = a[2:8]
print(b)
me str

Remember that strings are immutable. Thus, a[3] = 'x' does not replace the fourth character of a by x, but leads to an error message.

Line Breaks in String Literals#

Sometimes it’s necessary to use line breaks when specifying strings in source code. For this purpose Python knows triple quotes.

a = '''a very long string
spanning several lines
in source code'''

b = """another very long string
spanning several lines
in source code"""

print(a)
print(b)
a very long string
spanning several lines
in source code
another very long string
spanning several lines
in source code

As we see, line breaks in source code become part of the string. If this behavior is not desired, end each line with \.

a = '''a very long string\
spanning several lines\
in source code'''

print(a)
a very long stringspanning several linesin source code

A common pattern in Python source files is

a = '''\
first line
second line
last line\
'''
print(a)
first line
second line
last line

This way we get one-to-one correspondence between source code and screen output.

Note

A trailing \ tells Python that the souce code line continues on the next line, that is, that the next line break is not to be considered as line break. Usage is not restricted to strings. Long source code lines (longer than 80 characters) should be wrapped to multiple short lines.

Raw Strings#

To have line breaks and special characters in string literals we have to use escape sequences like \n, \", and so on. If we want to prevent the Python interpreter from translating escape sequences into corresponding characters, we may use raw strings. A raw string is taken as is by the interpreter. To mark a string literal as raw string prepend r.

a = r'Here is a line break:\nNow we are on a new line'
print(a)
print(type(a))
Here is a line break:\nNow we are on a new line
<class 'str'>

Useful Member Functions#

Read Python’s documentation of

to get an idea of what’s possible with string methods.