String Operations
Topics Covered:
● What is String in Python?
● How to create a string in Python?
● How to access characters in a string?
● How to change or delete a string?
● Python String Operations
● Python String Formatting
● Common Python String Methods
What is String in Python?
A string is a sequence of characters.
A character is simply a symbol. For example, the English language
has 26 characters.
Computers do not deal with characters, they deal with numbers
(binary). Even though you may see characters on your screen, internally
it is stored and manipulated as a combination of 0s and 1s.
This conversion of character to a number is called encoding, and the
reverse process is decoding. ASCII and Unicode are some of the
popular encodings used.
In Python, a string is a sequence of Unicode characters. Unicode was
introduced to include every character in all languages and bring
uniformity in encoding.
How to create a string in Python?
Strings can be created by enclosing characters inside a single quote or
double-quotes. Even triple quotes can be used in Python but generally
used to represent multiline strings and docstrings.
1
Example:-
Output:-
How to access characters in a string?
We can access individual characters using indexing and a range of
characters using slicing. Index starts from 0. Trying to access a character
out of index range will raise an IndexError. The index must be an integer.
We can't use floats or other types, this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so
on. We can access a range of items in a string by using the slicing
operator :(colon).
2
Example:-
Output:-
If we try to access an index out of the range or use numbers other than
an integer, we will get errors.
Example:-
Output:-
If we want to access a range, we need the index that will slice the
portion from the string.
3
How to change or delete a string?
Strings are immutable. This means that elements of a string cannot be
changed once they have been assigned. We can simply reassign
different strings to the same name.
Example:-
Output:-
We cannot delete or remove characters from a string. But deleting the
string entirely is possible using the del keyword.
Example:-
Output:-
Python String Operations
There are many operations that can be performed with strings which
makes it one of the most used data types in Python.
Concatenation of Two or More Strings
● Joining two or more strings into a single one is called
concatenation.
● The + operator does this in Python. Simply writing two string
literals together also concatenates them.
4
● The * operator can be used to repeat the string for a given number
of times.
Example:-
Output:-
Iterating Through a string
We can iterate through a string using a for loop. Here is an example to
count the number of 'l's in a string.
Example:-
Output:-
5
String Membership Test
We can test if a substring exists within a string or not, using the
keyword in.
Example:-
Output:-
Built-in functions to Work with Python
Various built-in functions that work with sequences work with strings as
well.
Some of the commonly used ones are enumerate() and len(). The
enumerate() function returns an enumerate object. It contains the
index and value of all the items in the string as pairs. This can be useful
for iteration.
Similarly, len() returns the length (number of characters) of the string.
Example:-
6
Output:-
Python String Formatting
Escape Sequence
If we want to print a text like He said, "What's there?", we can neither
use single quotes nor double quotes. This will result in a SyntaxError as
the text itself contains both single and double quotes.
Example:-
Output:-
One way to get around this problem is to use triple quotes. Alternatively,
we can use escape sequences.
An escape sequence starts with a backslash and is interpreted
differently. If we use a single quote to represent a string, all the single
quotes inside the string must be escaped. Similar is the case with
double quotes. Here is how it can be done to represent the above text.
7
Example:-
Output:-
Here is a list of all the escape sequences supported by Python.
Escape Sequence Description
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
8
Example:-
Output:-
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string.
To do this we can place r or R in front of the string. This will imply that it
is a raw string and any escape sequence inside it will be ignored.
Example:-
Output:-
9
The format() Method for Formatting Strings
The format() method that is available with the string object is very
versatile and powerful in formatting strings. Format strings contain
curly braces {} as placeholders or replacement fields which get replaced.
We can use positional arguments or keyword arguments to specify the
order.
Example:-
Output:-
10
The format() method can have optional format specifications. They are
separated from the field name using colon. For example, we can
left-justify <, right-justify > or center ^ a string in the given space.
We can also format integers as binary, hexadecimal, etc. and floats can
be rounded or displayed in the exponent format. There are tons of
formatting you can use.
Common Python String Methods
There are numerous methods available with the string object. The
format() method that we mentioned above is one of them. Some of the
commonly used methods are lower(), upper(), join(), split(), find(),
replace() etc. Here is a complete list of all the built-in methods to work
with strings in Python.
Example:-
Output:-
Python has a set of built-in methods that you can use on strings. They
are mentioned below.
11
Note: All string methods return new values. They do not change the
original string.
Method Description
capitalize() Converts the first character to uppercase
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the position
find() of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the position
index() of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
12
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
Returns a string where a specified value is replaced with a
replace() specified value
Searches the string for a specified value and returns the last
rfind() position of where it was found
Searches the string for a specified value and returns the last
rindex() position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to uppercase
translate() Returns a translated string
upper() Converts a string into upper case
Fills the string with a specified number of 0 values at the
zfill() beginning
13