Python String
Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes (for multiline strings). The computer does not understand the characters;
internally, it stores manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings
are also called the collection of Unicode characters.
Syntax:
str = "Hi Python !"
print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string
of length 1.
Creating String in Python
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string
"HELLO" is indexed as given below.
Consider the following example:
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[6]) # It returns the IndexError because 6th index doesn't exist
Output:
H
E
L
L
O
IndexError: string index out of range
The slice operator [] is used to access the individual characters of the string. We can use the :
(colon) operator in Python to access the substring from the given string.
Example 1
Example 2
# Given String
str = "TECHNO INDIA"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:9])
Output:
TECHNO INDIA
ECHN
CH
TEC
NO IN
We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on.
Ex3
Ex4
str = ' TECHNO INDIA '
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-20])
Output:
A
D
IA
NDI
O IND
AIDNI ONHCET
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object
doesn't support item assignment i.e., A string can only be replaced with new string since its
content cannot be partially replaced. Strings are immutable in Python.
Consider the following example.
Example 1
str = "HELLO"
str[0] = "h"
print(str)
Output:
Traceback (most recent call last):
File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment
However, in example 1, the string str can be assigned completely to a new content as specified
in example2.
Example 2
str = "HELLO"
print(str)
str = "hello"
print(str)
Output:
HELLO
hello
Deleting the String
We cannot delete or remove the characters from the string. But we can delete the entire string
using the del keyword.
str = "TECHNO"
del str[1]
Output:
TypeError: 'str' object doesn't support item deletion
Now we are deleting entire string.
str1 = "TECHNO"
del str1
print(str1)
Output:
NameError: name 'str1' is not defined
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either
side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of
the same string.
[] It is known as slice operator. It is used to access the sub-strings of a
particular string.
[:] It is known as range slice operator. It is used to access the characters
from the specified range.
in It is known as membership operator. It returns if a particular sub-string is
present in the specified string.
not in It is also a membership operator and does the exact reverse of in. It
returns true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such as
"C://python". To define any string as a raw string, the character r or R is
followed by the string.
% It is used to perform string formatting. It makes use of the format
specifiers used in C programming like %d or %f to map their values in
python.
Example 1
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1) # prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Python String Formatting
Escape Sequence
If we need to write the text as - They said, "Hello what's going on?"- the given statement can be
written in single quotes or double quotes but it will raise the SyntaxError as it contains both
single and double-quotes.
Example
str = "They said, "Hello what's going on?""
print(str)
Output:
SyntaxError: invalid syntax
We can use the triple quotes to accomplish this problem but Python provides the escape
sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a
special character and it interpreted differently. The single quotes inside the string must be
escaped. We can apply the same as in the double quotes.
Example -
# using triple quotes
print('''''They said, "What's there?"''')
# escaping single quotes
print('They said, "What\'s going on?"')
# escaping double quotes
print("They said, \"What's going on?\"")
Output:
They said, "What's there?"
They said, "What's going on?"
They said, "What's going on?"
The list of an escape sequence is given below:
Sr. Escape Sequence Description Example
1. \newline It ignores the new line. print("Python1 \
Python2 \
Python3")
Output:
Python1 Python2
Python3
2. \\ Backslash print("\\")
Output:
\
3. \' Single Quotes print('\'')
Output:
'
4. \\'' Double Quotes print("\"")
Output:
"
5. \a ASCII Bell print("\a")
6. \b ASCII Backspace(BS) print("Hello \b
World")
Output:
Hello World
7. \f ASCII Formfeed print("Hello \f
World!")
Hello World!
8. \n ASCII Linefeed print("Hello \n
World!")
Output:
Hello
World!
9. \r ASCII Carriege Return(CR) print("Hello \r
World!")
Output:
World!
10. \t ASCII Horizontal Tab print("Hello \t
World!")
Output:
Hello World!
11. \v ASCII Vertical Tab print("Hello \v
World!")
Output:
Hello
World!
12. \ooo Character with octal value print("\110\145\
154\154\157")
Output:
Hello
13 \xHH Character with hex value. print("\x48\x65\
x6c\x6c\x6f")
Output:
Hello
Here is the simple example of escape sequence.
print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
print("This is the \n multiline quotes")
print("This is \x48\x45\x58 representation")
Output:
C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation
We can ignore the escape sequence from the given string by using the raw string. We can do
this by writing r or R in front of the string. Consider the following example.
print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
Output:
C:\\Users\\DEVANSH SHARMA\\Python32
The format() method
The format() method is the most flexible and useful method in formatting strings. The curly
braces {} are used as the placeholder in the string and replaced by the format() method
argument. Let's have a look at the given an example:
# Using Curly braces
print("{} and {} both are the best friend".format("Devansh","Abhishek"))
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output:
Devansh and Abhishek both are the best friend
Rohit and Virat best players
James,Peter,Ricky
Python String Formatting Using % Operator
Python allows us to use the format specifiers used in C's printf statement. The format specifiers
in Python are treated in the same way as they are treated in C. However, Python provides an
additional operator %, which is used as an interface between the format specifiers and their
values. In other words, we can say that it binds the format specifiers to the values.
Integer = 10;
Float = 1.290
String = "Sourav"
print("Integer is %d\nfloat is %f\nstring is %s"%(Integer,Float,String))
Output:
Integer is 10
float is 1.290000
string is Sourav
Python String functions
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
capitalize() It capitalizes the first character of the String. This
function is deprecated in python3
casefold() It returns a version of s suitable for case-less
comparisons.
center(width ,fillchar) It returns a space padded string with the original
string centred with equal number of left and right
spaces.
count(string,begin,end) It counts the number of occurrences of a
substring in a String between begin and end
index.
decode(encoding = 'UTF8', errors = Decodes the string using codec registered for
'strict') encoding.
encode() Encode S using the codec registered for encoding.
Default encoding is 'utf-8'.
endswith(suffix It returns a Boolean value if the string terminates
,begin=0,end=len(string)) with given suffix between begin and end.
expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The
default space value is 8.
find(substring ,beginIndex, endIndex) It returns the index value of the string where
substring is found between begin index and end
index.
format(value) It returns a formatted version of S, using the
passed value.
index(subsring, beginIndex, endIndex) It throws an exception if string is not found. It
works same as find() method.
isalnum() It returns true if the characters in the string are
alphanumeric i.e., alphabets or numbers and
there is at least 1 character. Otherwise, it returns
false.
isalpha() It returns true if all the characters are alphabets
and there is at least one character, otherwise
False.
isdecimal() It returns true if all the characters of the string
are decimals.
isdigit() It returns true if all the characters are digits and
there is at least one character, otherwise False.
isidentifier() It returns true if the string is the valid identifier.
islower() It returns true if the characters of a string are in
lower case, otherwise false.
isnumeric() It returns true if the string contains only numeric
characters.
isprintable() It returns true if all the characters of s are
printable or s is empty, false otherwise.
isupper() It returns false if characters of a string are in
Upper case, otherwise False.
isspace() It returns true if the characters of a string are
white-space, otherwise false.
istitle() It returns true if the string is titled properly and
false otherwise. A title string is the one in which
the first character is upper-case whereas the
other characters are lower-case.
isupper() It returns true if all the characters of the string(if
exists) is true otherwise it returns false.
join(seq) It merges the strings representation of the given
sequence.
len(string) It returns the length of a string.
ljust(width[,fillchar]) It returns the space padded strings with the
original string left justified to the given width.
lower() It converts all the characters of a string to Lower
case.
lstrip() It removes all leading whitespaces of a string and
can also be used to remove particular character
from leading.
partition() It searches for the separator sep in S, and returns
the part before it, the separator itself, and the
part after it. If the separator is not found, return
S and two empty strings.
maketrans() It returns a translation table to be used in
translate function.
replace(old,new[,count]) It replaces the old sequence of characters with
the new sequence. The max characters are
replaced if max is given.
rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in
backward direction.
rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in
backward direction.
rjust(width,[,fillchar]) Returns a space padded string having original
string right justified to the number of characters
specified.
rstrip() It removes all trailing whitespace of a string and
can also be used to remove particular character
from trailing.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string
from the backward direction. It returns the list of
words in the string. If Separator is not specified
then the string splits according to the white-
space.
split(str,num=string.count(str)) Splits the string according to the delimiter str.
The string splits according to the space if the
delimiter is not provided. It returns the list of
substring concatenated with the delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with
newline removed.
startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with
given str between begin and end.
strip([chars]) It is used to perform lstrip() and rstrip() on the
string.
swapcase() It inverts case of all characters in a string.
title() It is used to convert the string into the title-case
i.e., The string meEruT will be converted to
Meerut.
translate(table,deletechars = '') It translates the string according to the
translation table passed in the function .
upper() It converts all the characters of a string to Upper
Case.
zfill(width) Returns original string leftpadded with zeros to a
total of width characters; intended for numbers,
zfill() retains any sign given (less one zero).
Max
Min
Python String capitalize() Method
Python capitalize() method converts first character of the string into uppercase without altering
the whole string. It changes the first character only and skips rest of the string unchanged.
Example
str = "technoIndia" # Variable declaration
str2 = str.capitalize() # Calling function
print("Old value:", str) # technoIndia
print("New value:", str2) # TechnoIndia
# if first character already exist in uppercase. It returns the same string without any alteration.
str = " TechnoIndia "
str2 = str.capitalize()
print("Old value:", str) # TechnoIndia
print("New value:", str2) # TechnoIndia
# if first character is a digit or non-alphabet character, it does not alter character if it is other than a
string character.
str = "$technoIndia" # Variable declaration
str2 = str.capitalize() # Calling function
print("Old value:", str) # $technoIndia
print("New value:", str2) # $technoIndia
str = "1-technoIndia" # Variable declaration
str2 = str.capitalize() # Calling function
print("Old value:", str) # 1-technoIndia
print("New value:", str2) # 1-technoIndia
Python String Count() Method
It returns the number of occurences of substring in the specified range. It takes three
parameters, first is a substring, second a start index and third is last index of the range. Start
and end both are optional whereas substring is required.
Ex1
str = "Hello TechnoIndia" # Variable declaration
str2 = str.count('n')
print("occurences:", str2) # Displaying result occurences: 2
Ex 2
# Python count() function example
str = "ab bc ca de ed ad da ab bc ca" # Variable declaration
oc1 = str.count('a')
oc2 = str.count('a', 3)
oc3 = str.count('a', 3, 8)
print("occurences:", oc1) #occurences: 6
print("occurences:", oc2) #occurences: 5
print("occurences:", oc3) #occurences: 1
Ex3
# Python count() function example
str = "ab bc ca de ed ad da ab bc ca 12 23 35 62"
oc = str.count('2')
print("occurences:", oc) #occurences: 3
Python String find() Method
Python find() method finds substring in the whole string and returns index of the first match. It
returns -1 if substring does not match.
Ex 1
# Python find() function example
str = "Welcome to TechnoIndia." # Variable declaration
str2 = str.find("to") # Calling function
str3 = str.find("is")
# Displaying result
print(str2) # Displaying result 8
print(str3) # Displaying result -1 (It returns -1 if not found any match)
str4 = str.find("o")
str5 = str.find("o",20)
str6 = str.find("o",13,21)
print(str4) # Displaying result 9
print(str5) # Displaying result -1
print(str6) # Displaying result 16
Python String isalnum() Method
Python isalnum() method checks whether the all characters of the string is alphanumeric or
not. A character which is either a letter or a number is known as alphanumeric. It does not
allow special chars even spaces.
Ex 1
# Python isalnum() function example
str = "Welcome"
str2 = str.isalnum()
print(str2) # True #alphabets is allowed
str = " Welcome"
str2 = str.isalnum()
print(str2) # False # space is not allowed anywhere in the string
str = "Welcome123"
str1 = "Welcome 123"
str2 = str.isalnum()
str4 = str1.isalnum()
print(str2) # True #alphanumeric is allowed
print(str4) # False # space is not allowed anywhere in the string
str = "123456"
str2 = str.isalnum()
print(str2) # True #string with digits is allowed
Python String isalpha() Method
Python isalpha() method returns true if all characters in the string are alphabetic. It returns
False if the characters are not alphabetic.
Ex 1
# Python isalpha() method example
str = "TechnoIndia"
str2 = str.isalpha()
print(str2) # True # alphabets are only allowed
str = "Techno India"
str2 = str.isalpha()
print(str2) # False # space is not allowed
Ex 2
str = "TechnoIndia"
if str.isalpha() == True:
print("String contains alphabets")
else: print("Stringn contains other chars too.")
Output:
String contains alphabets
Python String isdigit() Method
Python isdigit() method returns True if all the characters in the string are digits. It returns False
if no character is digit in the string.
Ex 1
str = '12345'
str2 = str.isdigit()
print(str2) # True # digits are only allowed
str3 = "120-2569-854"
str4 = str3.isdigit()
print(str4) # False # digits are only allowed
Ex2
str = "123!@#$"
if str.isdigit() == True:
print("String is digit")
else:
print("String is not digit")
Output:
String is not digit
Python String isnumeric() Method
Python isnumeric() method checks whether all the characters of the string are numeric
characters or not. It returns True if all the characters are true, otherwise returns False.
Numeric characters include digit characters and all the characters which have the Unicode
numeric value property.
Ex 1
# Python isnumeric() method example
str = "12345"
str2 = str.isnumeric()
print(str2) # True # numeric values are allowed
str = "techno12345"
str2 = str.isnumeric()
print(str2) # False # only numeric values are allowed
Ex2
str = "123452500" # True
if str.isnumeric() == True:
print("Numeric")
else:
print("Not numeric")
str2 = "123-4525-00" # False
if str2.isnumeric() == True:
print("Numeric")
else:
print("Not numeric")
Output:
Numeric
Not numeric
Python String isupper() Method
Python isupper() method returns True if all characters in the string are in uppercase. It returns
False if characters are not in uppercase.
Ex 1
# Python isupper() method example
str = "WELCOME TO TECHNOIDIA"
str2 = str.isupper()
print(str2) # True # uppercase letters are allowed
str3 = "Welcome to Techno India"
str4 = str3.isupper()
print(str4) # False # uppercase letters are only allowed
Ex2
str5 = "123 @#$ -JAVA."
str6 = str5.isupper()
print(str6) # True # special characters & spaces are also allowed, except
lower case letters
Python String islower() Method
Python string islower() method returns True if all characters in the string are in lowercase. It
returns False if not in lowercase.
Ex 1
# Python islower() method example
str = "technoindia"
str2 = str.islower()
print(str2) # True # lowercase letters are allowed
str = "TechnoIndia"
str2 = str.islower()
print(str2) # False # lowercase letters are only allowed
Ex 2
str = "hi, my contact is 9856******"
str2 = str.islower()
print(str2) # True #String can have digits also and this method works in letters case
and ignores digits.
Python String isspace() Method
Python isspace() method is used to check space in the string. It return a true if there are only
whitespace characters in the string. Otherwise it returns false. Space, newline, and tabs etc are
known as whitespace characters and are defined in the Unicode character database as Other or
Separator.
Ex1
# Python isspace() method example
str = " " # empty string
str2 = str.isspace()
print(str2) # True
str = "ab cd ef" # string contains spaces
str2 = str.isspace()
print(str2) # False
isspace() method returns true for all whitespaces like:
o ' ' - Space
o '\t' - Horizontal tab
o '\n' - Newline
o '\v' - Vertical tab
o '\f' - Feed
o '\r' - Carriage return
Ex2
# Python isspace() method example
# Variable declaration
str = " " # string contains space
if str.isspace() == True:
print("It contains space")
else:
print("Not space")
str = "ab cd ef \n"
if str.isspace() == True:
print("It contains space")
else:
print("Not space")
str = "\t \r \n"
if str.isspace() == True:
print("It contains space")
else:
print("Not space")
Output:
It contains space
Not space
It contains space
Python String join() Method
Python join() method is used to concat a string with iterable object. It returns a new string
which is the concatenation of the strings in iterable. It throws an exception TypeError if iterable
contains any non-string value.
It allows various iterables like: List, Tuple, String etc.
Ex 1
# Python join() method example
str = ":" # string
list = ['1','2','3'] # iterable
str2 = str.join(list)
print(str2)
Output:
1:2:3
Ex 2
A list iterable join with empty string and produce a new string.
# Python join() method example
# Variable declaration
str = "" # string
list = ['J','a','v','a'] # iterable
str2 = str.join(list)
print(str2) # java
Ex 3
An example of join() method with Set iterable. Set contains unordered elements and produce
different output each times.
# Python join() method example
str = "->" # string
list = {'Java','C#','Python'} # iterable
str2 = str.join(list)
print(str2)
Output:
Java->Python->C#
Ex 4
In case of dictionary, this method join keys only. Make sure keys are string, otherwise it
throws an exception.
# Python join() method example
dict = {'key1': 1, 'key2': 2}
str = '&'
str = str.join(dict)
print(str)
Output:
key1&key2
Python String split() Method
Python split() method splits the string into a comma separated list. It separates string based on
the separator delimiter. This method takes two parameters and both are optional.
Ex 1
usage of split() method. No parameter is given, by default whitespaces work as separator.
# Python split() method example
str = "Java is a programming language"
str2 = str.split()
print(str)
print(str2)
Output:
Java is a programming language
['Java', 'is', 'a', 'programming', 'language']
Ex 2
Pass a parameter separator to the method, now it will separate the string based on the
separator.
# Python split() method example
str = "Java is a programming language"
str2 = str.split('Java')
print(str2)
Output:
['', ' is a programming language']
Ex 3
The string is splited each time when a is occurred
# Python split() method example
str = "Java is a programming language"
str2 = str.split('a')
print(str)
print(str2)
Output:
Java is a programming language
['J', 'v', ' is ', ' progr', 'mming l', 'ngu', 'ge']
Ex 4
Along with separator, we can also pass maxsplit value. The maxsplit is used to set the number
of times to split.
# Python split() method example
str = "Java is a programming language"
str2 = str.split('a',1)
print(str2)
str2 = str.split('a',3)
# Displaying result
print(str2)
Output:
['J', 'va is a programming language']
['J', 'v', ' is ', ' programming language']
Python String replace() Method
Return a copy of the string with all occurrences of substring old replaced by new. If the optional
argument count is given, only the first count occurrences are replaced.
Ex 1
# Python replace() method example
str = "Java C C# Java Php Python Java"
str1 = str.replace("Java","C#") # replaces all the occurences
print("Old String: \n",str)
print("New String1: \n",str1)
str2 = str.replace("Java","C#",1) # replaces first occurance only
print("New String2: \n",str2)
Output:
Old String:
Java C C# Java Php Python Java
New String1:
C# C C# C# Php Python C#
New String2:
C# C C# Java Php Python Java
Ex 2
# Python replace() method example
str = "Apple is a fruit"
str2 = str.replace(str,"Tomato is also a fruit")
print(str2)
Output:
Tomato is also a fruit
Python String lower() Method
Python lower() method returns a copy of the string after converting all the characters into
lowercase.
Ex 1
# Python lower() method example
str = "TechnoIndia"
str = str.lower()
print(str) # technoindia
str = "Welcome To TECHNOIndia"
str = str.lower()
print(str) # welcome to technoindia
Python String upper() Method
Python uuper() method returns a copy of the string after converting all the characters into
uppercase.
Ex 1
# Python upper() method example
str = "TechnoIndia"
str = str.upper()
print(str) # TECHNOINDIA
str = "Welcome To TECHNOIndia"
str = str.upper()
print(str) # WELCOME TO TECHNOINDIA