Strings in Python

In this article, we’ll discuss about strings in python and most of the string operations in python.

Strings in python with examples

Introduction to strings in Python

A string is used to store text or a collection of UNICODE characters. Strings can be used to represent just about anything that can be encoded as text or bytes. In python, there is no distinct type for single characters. Also, strings are immutable sequences, that means they cannot be changed in place.

Defining strings in python

Strings in python can be defined by following methods:

>>> string1 = '' 
>>> string2 = "single or double quoted strings are the same" 
>>> string3 = '''Triple quotes are used
... for writing multiline strings and 
... this is an example string'''
>>> print(string1)
>>> print(string3) Triple quotes are used for writing multiline strings and this is an example string 
Screenshot of the code in the interactive python prompt

String operations in python:

1. Print the length of a string:

This is a python string example program to print the length of string on screen.

>>> str = "use in-built function len(string)." 
>>> print(len(str)) 34 
Length of a string in python
Screenshot of code in the interactive prompt

2. Concatenation and repetition of strings

Concatenation means joining two or more strings into single string. In python, this is done by using ‘+’ operator. To repeat a string, ‘*’ operator is used between the string and the number of times.

This is a python string example that helps in understanding concatenation of strings in python.

>>> str1 = "Concatenation of"
>>> str2 = 'strings'
>>> print(str1 + str2)
Concatenation ofstrings     #str2 added to str1 without space.
>>> print('Python' * 3)

Recommended reading:

Is python hard to learn? What are some of the best resources to learn python?

3. How to access characters in a string?

Python does not have character data type, but individual characters can be accessed and used by indexing.

This python string example program helps in understanding how to access characters of a string.

>>> str = "programming-articles"
>>> str[3]
>>> str[11]
>>> str[0]

4. How to change a string?

In python, a string is immutable, so it cannot be changed in place, but we can assign a new string to the same name.

This python string example program changes the data inside a string, given that python strings in python are immutable.

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


>>> str = str[:2] + 'o' + str[3:] 
>>> str 'ProgrammingMadeEasy'

5. How to print the characters of a string, separated with a space?

This is a python string example to print the characters of a string separated with a space.

>>> str = 'Python'
>>> for char in str:
...     print(char, end=' ')
P y t h o n

6. Indexing and string slicing in python:

Strings in python are ordered, so their elements(characters) can be accessed by their position and this position is known as it’s “index”. In python, negative indexing is also allowed for reverse operations.

This python string example implements indexing and slicing of a string in python.

>>> hobby = 'programming'
>>> hobby[2]         #print a character
>>> hobby[3:7]     #print a section(notice: 7 excluded)
>>> hobby[-1]       #negative indexing starts from -1

The indexing pattern is as follows:

7. Extended slicing of a string:

Extended slicing is done by using the optional third index, known as step or stride. It has default value of 1, it means that while iterating over the string, it changes its value by 1 only. If step is 2, alternate elements are printed. If step is negative, elements are printed from right to left while skipping elements according to the step number provided.

The following python string examples implements extended slicing of a string in python.

>>> str = 'SampleString'
>>> str[2:8:2]
>>> str[::2]
>>> str[7:1:-1]
>>> str[::-1]        #reversing a string
>>> str[::-3]

8. String membership test in python:

This python string example program checks whether a character or a string is a part of the string provided.

>>> 'p' in "programming"
>>> 'm' in "PROGRAMMING"
>>> 'M' in "PROGRAMMING"

9. String formatting in python:

This is one of the most important application or string operations in python, go through it with complete dedication and concentration.

>>> print('He said,"What's the update?"')
  File "<stdin>", line 1
    print('He said,"What's the update?"')
SyntaxError: invalid syntax

The above results into error because the string contains both single and double quotes and this is not allowed in any programming language because the compiler gets confused whether to consider the inner quotes or the outer ones. To overcome such type of issues, escape sequences are introduced. Escape sequences are used to embed characters in strings that cannot easily be typed on a keyboard. A backslash is used to introduce a escape sequence characters.

Below is a python example program to implement string formatting in python.

>>> print('He said,"What\'s the update?"')      #no backslash for "
He said,"What's the update?"
>>> print("He said,\"What's the update?\"")     #no backslash for '
He said,"What's the update?"
>>> print('''"He said,"What's the update?"''')   #by using triple quotes
"He said,"What's the update?"

In the above example, we noticed that no escape sequence is needed for double quotes when the string is quoted inside single quotes and when string is inside double quotes, no backslash is needed for the single quotes.

List of commonly used escape sequence characters:

Escape SequenceDescription
\newlineBackslash and newline ignored
\’Single quote
\”Double quote
\rCarriage Return
\tHorizontal Tab
\vVertical Tab
\oooCharacter with octal value ooo(upto 3 digits)
\xHHCharacter with hexadecimal value hh(exactly 2 digits)
\0 Null: binary 0 character (doesn’t end string)

10. Raw strings in python:

If we want to ignore the escape sequence in a string, the string is marked as a raw string by adding r or R before the string. Just remember that a raw string cannot end in an odd number of backslashes.

>>> print('He said,\"What\'s the update?"')     #without using r or R
He said,"What's the update?"
>>> print(r'He said,\"What\'s the update?"')     #declaring as raw string
He said,\"What\'s the update?"

11. String formatting in python (*important)

String formatting is a very important topic in python, so revise this section at least 3-4 times and keep experimenting.

To understand this we will take example of the alert message of an application in our phones by the operating system. For example, "WhatsApp wants access to your photos!" or "Twitter wants access to your Contacts!". Operating system would not generate a different string message for every alert, it will just format the string to change the name of the application and the feature it wants to access.

String formatting makes it easier to update and maintain code. For example, to change the name and feature for different cases in the above example, you just have to make changes to the name and feature objects.

11-a . String formatting in python using % operator

The following python example program implements string formatting using % operator.

>>> actor= "Ryan Gosling"
>>> str = "My favorite actor is %s." %actor
>>> print(str)
My favorite actor is Ryan Gosling.

Here, % is used to locate the position where substitution will be done and s is the type/conversion specifier for strings. For multiple substitutions, values are given in parentheses and multiple % are used.

>>> app = "WhatsApp" 
>>> feature = "Photos" 
>>> str = "%s wants access to your %s!"%(app, feature) 
>>> print(str) 
WhatsApp wants access to your Photos!
>>> app = "Twitter" 
>>> feature = "Contacts" 
>>> str = "%s wants access to your %s!"%(app, feature) 
>>> print(str) 
Twitter wants access to your Contacts!
>>> print("%s is %d years old."%("Monica", 25))
Monica is 25 years old.

11-b . String formatting in python using mapping:

String formatting can be done providing substitute values using mapping also. The following python example program implements string formatting in python using mapping.

>>> name = "Monica"
>>> age = 25
>>> print("%(name)s is %(age)d years old." % {
...     "name": name, "age": age})
Monica is 25 years old.

11-c . String formatting in python using format()

Python introduced a new way to format strings without using % operator. The format() method of string objects is available in Python 2.6, 2.7, and 3.X. To use this feature, you need to know about functions and function calls.

Below is a python string example to implement string formatting in python using format() method.

>>> str = "My favorite actor is {}.".format(actor)
>>> print(str)
My favorite actor is Ryan Gosling.

For multiple substitutions we put values in parentheses like in old method.

>>> str = "{app} wants access to your {feature}!".format(
...     app= app, feature= feature)
>>> print(str)
Twitter wants access to your Contacts!
>>> info = "{1} is {0} years old.".format(31, "Chandler")
>>> print(info) 
Chandler is 31 years old.

In the above example, 1 and 0 are the indices of references provided inside format(). 31 is a index 0 and “Chandler” is at position 1 hence the string becomes like that.

11-d . Interpolation or f-strings in Python:

Python 3.6 introduced a new string formatting technique known as Literal interpolation of strings or f-strings. To create an f-string, letter ” f ” is added in front of the string. Try to understand the implementation using the following python example program.

>>> a = 43
>>> b = 59
>>> str = f"The sum of {a} and {b} is {a+b}."
>>> print(str)
The sum of 43 and 59 is 102.

f-strings are a bit similar to formatting using format() but for Python 3.6+ users, f-strings are recommended.

String methods in python

Most of the string operations include type-specific functions (methods). Therefore, to know more about string-specific functions, visit official website of Python.

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →

Leave a Reply

Your email address will not be published. Required fields are marked *