Strings in Python 3

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)

Further reading about escape sequences here.

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



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

<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'
ing conte
string con
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.

TypeError: 'str' object does not support item assignment

To learn more about text processing refer this link.

A quick note about why I am not explaining all the string processing services and string methods: I just need to know, at a high level, what string processing resources exist and where to find them when the need arises. Spending time trying out all the methods and services is not very efficient or interesting. Let me reiterate that I will be learning on the fly.

Code for today’s plog is available here.