Python Class 3a - String
Python Class 3a - 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:
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.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Like other languages, the indexing of the Python strings starts from 0. For example, The string
"HELLO" is indexed as given below.
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
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.
Example 1
str = "HELLO"
str[0] = "h"
print(str)
Output:
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:
str1 = "TECHNO"
del str1
print(str1)
Output:
String Operators
Operator Description
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.
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
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
Output:
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 -
2. \\ Backslash print("\\")
Output:
\
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 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:
#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:
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 provides various in-built functions that are used for string handling. Many String fun
Method Description
decode(encoding = 'UTF8', errors = Decodes the string using codec registered for
'strict') encoding.
find(substring ,beginIndex, endIndex) It returns the index value of the string where
substring is found between begin index and end
index.
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
# 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.
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
Ex 2
Ex3
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
str4 = str.find("o")
str5 = str.find("o",20)
str6 = str.find("o",13,21)
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
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
Ex 2
str = "TechnoIndia"
if str.isalpha() == True:
print("String contains alphabets")
else: print("Stringn contains other chars too.")
Output:
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:
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
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")
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
Ex2
str5 = "123 @#$ -JAVA."
str6 = str5.isupper()
print(str6) # True # special characters & spaces are also allowed, except
lower case letters
Python string islower() method returns True if all characters in the string are in lowercase. It
returns False if not in lowercase.
Ex 1
Ex 2
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
Ex2
# Python isspace() method example
# Variable declaration
str = " " # string contains space
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.
Ex 1
Output:
1:2:3
Ex 2
A list iterable join with empty string and produce a new string.
Ex 3
An example of join() method with Set iterable. Set contains unordered elements and produce
different output each times.
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.
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
Output:
Ex 2
Pass a parameter separator to the method, now it will separate the string based on the
separator.
Output:
Ex 3
Output:
Ex 4
Along with separator, we can also pass maxsplit value. The maxsplit is used to set the number
of times to split.
str2 = str.split('a',3)
# Displaying result
print(str2)
Output:
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
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
Output:
Python lower() method returns a copy of the string after converting all the characters into
lowercase.
Ex 1
Python uuper() method returns a copy of the string after converting all the characters into
uppercase.
Ex 1