Python Strings Example

In this article, we will explain Strings in Python.

1. Introduction

Python is an easy-to-learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site,, and may be freely distributed. The same site also contains distributions of and pointers to many free third-party Python modules, programs and tools, and additional documentation.

2. Pyhton Strings

Strings in Python can be represented in single (‘sample string in single quote’) quotes or double (“sample string in double-quotes”) quotes.

>>> 'sample string - single quote'
'sample string - single quote'
>>> "sample string in double quote"
'sample string in double quote'

We can use backspace (‘\’) character as the escape character

>>> 'doesn't'
  File "<stdin>", line 1
SyntaxError: invalid syntax
>>> 'doesn\'t'

If you are using double quotes then you don’t need the escape character:

>>> "doesn't"

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes.

2.1 Raw strings

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

>>> print('My home directory \n is here')
My home directory
 is here
>>> print(r'My home directory \n is here')
My home directory \n is here

2.2 Multi-line strings

String literals can span multiple lines. One way is by using triple-quotes ''' ... ''' or """ ...... """. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

>>> print(""" This
... is
... a
... multi-line test
... """)
multi-line test

2.3 Repetition and Concatenation

Strings can be concatenated by using the + operator:

>>> 'This is a' + 'concatenation example'
'This is aconcatenation example'

You can use the * operator to repeat the string:

>>> 3 * 'Repeat me three times > '
'Repeat me three times > Repeat me three times > Repeat me three times > '

If the strings are next to each other, we don’t need the + operator:

>>> 'you ' 'don\'t ' 'need ' 'a ' '\'+\' ' 'here'
"you don't need a '+' here"

This only works with two literals though, not with variables or expressions:

>>> a = 'Hello'
>>> a 'World'
  File "<stdin>", line 1
    a 'World'
SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use + operator

>>> a + 'World'

2.4 Indexing and slicing

Strings can be indexed using []:

>>> test = "Hello World"
>>> test[0]
>>> test[5]
' '

Indices may also be negative numbers, to start counting from the end. Note that since -0 is the same as 0, negative indices start from -1.

>>> test[-1]
>>> test[-8]

While indexing is used to obtain individual characters, slicing allows you to obtain substring. Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> test[0:5]
>>> test[6:11]
>>> test[:11]
'Hello World'
>>> test[6:]
>>> test[-5:]

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n.

Attempting to use an index that is too large will result in an error:

>>> test[12]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

However, out of range slice indexes are handled gracefully when used for slicing:

>>> test[0: 22]
'Hello World'

2.5 Immutability

Python strings are immutable. What this means is that once created they can’t be changed.

>>> test[2] = 'A'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

If you need a different string, you should create a new one

>>> test[:5] + ' Coders'
'Hello Coders'

len() returns the length of the string:

>>> len(test)

3. String methods

In this section, we will discuss some most commonly used methods in String class.

3.1 capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased:

>>> "capital".capitalize()

3.2 count()

This method will return the number of occurrences of the substring.

>>> "is the is not".count("is")
>>> "is the is not".count("not")

3.3 endswith()

Return True if the string ends with the specified suffix, otherwise return False:

>>> "Jaca Code Geeks Example".endswith("ple")
>>> "Jaca Code Geeks Example".endswith("Exa")

3.4 find(“sub”)

Returns the lowest index in the string where the substring sub is found:

>>> "Jaca Code Geeks Example".find("Geeks")
>>> "Jaca Code Geeks Example".find("Heek")

The find() method should be used only if you need to know the position of the substring. To check if the substring exists or not, use the in operator

4. Summary

In this article, we learned how to use Strings in Python. First, we looked at the different ways how we can use Strings. Then we looked at different types of operators which can be used with the strings. In the end, we discussed some commonly used methods in String class.

Mohammad Meraj Zia

Senior Java Developer
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button