Strings are sequences of characters.

Strings can be written in the following ways:

• ‘single quotes’
• “double quotes”
• ”‘multi line”’

Escape sequences are used to display characters with a special meaning such as ', " , \ within a string.

Some examples:

• \\ displays \
• \" displays "
• \' displays '
• \n displays a new line (LF)

To find the length a string, the len() function can be used.

Example:

len('String')
6


To convert other datatypes to a string, the str() function can be used.

mystr=str(100)
type(mystr)
<class 'str'>


There are built in methods available to perform common operations/transformations in Python. Some of them can be found here. I won’t show the usage of the functions here though.

I will talk about slicing strings very briefly. A slice is a segment of the string. The following code demonstrates how to slice a string.

slice_example='string contents'
print(slice_example[3:12])
ing conte
print(slice_example[:10])
string con
print(slice_example[4:])
ng contents


The operator [n:m] returns the string from the n-th character to the m-th character, including the n-th character and excluding the m-th character. If n is omitted, it starts from the first character. If m is omitted, it ends with the last character.

An important property of strings is that, they are immutable. The following example demonstrates this property.

s='abc'
s[0]='x'
TypeError: 'str' object does not support item assignment