Python Strings
Python Strings
Strings
• A string is a sequence of characters.
• We use single quotes or double quotes to represent a string in Python.
• For example,
# create a string using double quotes
string1 = "Python programming"
• The Python String split() method splits all the words in a string separated by a specified
separator.
• This separator is a delimiter string, and can be a comma, full-stop, space character or
any other character used to separate strings.
• Syntax
• string.split(separator, maxsplit)
• str.split(str="", num=string.count(str)).
Deleting/Updating from a String
• In Python, the Updation or deletion of characters from a String is not
allowed.
• This will cause an error because item assignment or item deletion
from a String is not supported.
• Although deletion of the entire String is possible with the use of a
built-in del keyword.
• This is because Strings are immutable, hence elements of a String
cannot be changed once it has been assigned.
• Only new strings can be reassigned to the same name.
Updation of a character:
# Python Program to Update character of a String
String1 = "Hello, I'm from New Horizon college of ENgineering"
print("Initial String: ")
print(String1)
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Deleting the String:
• Deletion of the entire string is possible with the use of del keyword.
• Further, if we try to print the string, this will produce an error because String is deleted and is
unavailable to be printed.
• # Python Program to Delete
# entire String
String1 = “New Horizon college of engineering"
print("Initial String: ")
print(String1)
# Deleting a String with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Escape Sequencing in Python
• While printing Strings with single and double quotes in it causes
SyntaxError because String already contains Single and Double Quotes
and hence cannot be printed with the use of either of these.
• Hence, to print such a String either Triple Quotes are used or Escape
sequences are used to print such Strings.
• Escape sequences start with a backslash and can be interpreted
differently. If single quotes are used to represent a string, then all the
single quotes present in the string must be escaped and same is done
for Double Quotes.
Formatting of Strings
• Strings in Python can be formatted with the use of format() method which is a very versatile and powerful tool for formatting Strings.
• Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to
specify the order.
• # Python Program for # Formatting of Strings
# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
String Operators in Python
• Assignment operator: “=.”
• Concatenate operator: “+.”
• String repetition operator: “*.”
• String slicing operator: “[]”
• String comparison operator: “==” & “!=”
• Membership operator: “in” & “not in”
• Escape sequence operator: “\.”
• String formatting operator: “%” & “{}”
Assignment Operator “=”
• Python string can be assigned to any variable with an assignment
operator “= “.
• Python string can be defined with either single quotes [‘ ’], double
quotes[“ ”] or triple quotes[‘’’ ‘’’]. var_name = “string” assigns
“string” to variable var_name.
Concatenate Operator “+”
• Two strings can be concatenated or join using the “+” operator in
python, as explained in the below example code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
String repetition operator: “*”
• The same string can be repeated in python by n times using string*n,
as explained in the below example.
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
String slicing operator “[]”
• Characters from a specific index of the string can be accessed with the string[index] operator. The index is interpreted as a
positive index starting from 0 from the left side and a negative index starting from -1 from the right side.
• string[a]: Returns a character from a positive index a of the string from the left side as displayed in the index graph above.
• string[-a]: Returns a character from a negative index a of the string from the right side as displayed in the index graph above.
• string[a:b]: Returns characters from positive index a to positive index b of the as displayed in index graph above.
• string[a:-b]: Returns characters from positive index a to the negative index b of the string as displayed in the index graph above.
• string[a:]: Returns characters from positive index a to the end of the string.
• string[:b] Returns characters from the start of the string to the positive index b.
• string[-a:]: Returns characters from negative index a to the end of the string.
• string[:-b]: Returns characters from the start of the string to the negative index b.
• string[::-1]: Returns a string with reverse order.
String slicing operator “[]”
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
String comparison operator: “==” & “!=”
• The string comparison operator in python is used to compare two strings.
• “==” operator returns Boolean True if two strings are the same and return Boolean False if two strings are not the
same.
• “!=” operator returns Boolean True if two strings are not the same and return Boolean False if two strings are the
same.
• These operators are mainly used along with if condition to compare two strings where the decision is to be taken
based on string comparison.
• Example:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
Membership Operator “in” & “not in”
• Membership operator is used to searching whether the specific character is part/member of a given
input python string.
• “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in the string.
• “a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a” is in the string.
• A membership operator is also useful to find whether a specific substring is part of a given string.
• string1 = "helloworld“
• Example:
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)
Escape Sequence Operator “\”
• To insert a non-allowed character in the given input string, an escape
character is used.
• An escape character is a “\” or “backslash” operator followed by a
non-allowed character.
• An example of a non-allowed character in python string is inserting
double quotes in the string surrounded by double-quotes.
• Example:
string = "Hello world I am from \"India\""
print(string)
String Formatting Operator “%”
• String formatting operator is used to format a string as per requirement.
• To insert another type of variable along with string, the “%” operator is
used along with python string. “%” is prefixed to another character
indicating the type of value we want to insert along with the python string.
• Please refer to the below table for some of the commonly used different
string formatting specifiers:
Operator Description
%d Signed decimal integer
%u unsigned decimal integer
%c Character
%s String
%f Floating-point real number
String Formatting Operator “%”
• name = "india"
• age = 19
• marks = 20.56
• string1 = 'Hey %s' % (name)
• print(string1)
• string2 = 'my age is %d' % (age)
• print(string2)
• string3= 'Hey %s, my age is %d' % (name, age)
• print(string3)
• string3= 'Hey %s, my subject mark is %f' % (name, marks)
• print(string3)
Python String functions
Function Description
format() It’s used to create a formatted string from the template string and the supplied values.
split() Python string split() function is used to split a string into the list of strings based on a delimiter.
join() This function returns a new string that is the concatenation of the strings in iterable with string object as a delimiter.
replace() Python string replace() function is used to create a new string by replacing some parts of another string.
find() Python String find() method is used to find the index of a substring in a string.
Python String functions
Function Description
encode() Python string encode() function is used to encode the string using the provided encoding.
count() Python String count() function returns the number of occurrences of a substring in the given string.
startswith() Python string startswith() function returns True if the string starts with the given prefix, otherwise it returns False.
endswith() Python string endswith() function returns True if the string ends with the given suffix, otherwise it returns False.
capitalize() Python String capitalize() function returns the capitalized version of the string.
center() Python string center() function returns a centered string of specified size.
Python string casefold() function returns a casefolded copy of the string. This function is used to perform case-insensitive string
casefold()
comparison.
Python String functions
Function Description
isalnum() Python string isalnum() function returns True if it’s made of alphanumeric characters only.
isalpha() Python String isalpha() function returns True if all the characters in the string are alphabets,
otherwise False.
Python String isdecimal() function returns True if all the characters in the string are decimal
isdecimal() characters, otherwise False.
Python String isdigit() function returns True if all the characters in the string are digits,
isdigit() otherwise False.
isidentifier() Python String isidentifier() function returns True if the string is a valid identifier according
to the Python language definition.
Python String islower() returns True if all cased characters in the string are lowercase and
islower()
there is at least one cased character, otherwise it returns False.
isnumeric() Python String isnumeric() function returns True if all the characters in the string are
numeric, otherwise False. If the string is empty, then this function returns False.
Python String functions
Function Description
isalnum() Python string isalnum() function returns True if it’s made of alphanumeric characters only.
isalpha() Python String isalpha() function returns True if all the characters in the string are alphabets, otherwise False.
isdecimal() Python String isdecimal() function returns True if all the characters in the string are decimal characters, otherwise False.
isdigit() Python String isdigit() function returns True if all the characters in the string are digits, otherwise False.
isidentifier() Python String isidentifier() function returns True if the string is a valid identifier according to the Python language definition.
Python String islower() returns True if all cased characters in the string are lowercase and there is at least one cased character, otherwise it returns
islower() False.
Python String isnumeric() function returns True if all the characters in the string are numeric, otherwise False. If the string is empty, then this function
isnumeric()
returns False.
isprintable() Python String isprintable() function returns True if all characters in the string are printable or the string is empty, False otherwise.
isspace() Python String isspace() function returns True if there are only whitespace characters in the string, otherwise it returns False.
istitle() Python String istitle() returns True if the string is title cased and not empty, otherwise it returns False.
isupper() Python String isupper() function returns True if all the cased characters are in Uppercase.
rjust(), ljust() Utility functions to create a new string of specified length from the source string with right and left justification.
swapcase() Python String swapcase() function returns a new string with uppercase characters converted to lowercase and vice versa.
partition() Python String partition() function splits a string based on a separator into a tuple with three strings.
splitlines() Python String splitlines() function returns the list of lines in the string.
title() Python String title() function returns a title cased version of the string.
zfill() Python String zfill(width) function returns a new string of specified width. The string is filled with 0 on the left side to create the specified width.
FILE HANDLING
• Python too supports file handling and allows users to handle files i.e., to
read and write files, along with many other file handling options, to operate
on files.
• in Python, files are treated in two modes as text or binary.
• The file may be in the text or binary format, and each line of a file is ended
with the special character.
• Hence, a file operation can be done in the following order.
• Open a file
• Read or write - Performing operation
• Close the file
FILE HANDLING
• f = open(filename, mode)
• Where the following mode is supported:
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some
data then it will be overridden but if the file is not present then it creates the
file as well.
• a: open an existing file for append operation. It won’t override existing data.
Working in Read mode
• The open command will open the file in the read mode and the for
loop will print each line present in the file.
• Example:
# a file named “college", will be opened with the reading mode.
file = open(‘college.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
Read Mode
• In this example, we will extract a string that contains all characters in
the file then we can use file.read().
• # Python code to illustrate read() mode
file = open(“college.txt", "r")
print (file.read())
Read Mode
• In this example, we will see how we can read a file using the with
statement.
• # Python code to illustrate with()
• with open(“college.txt") as file:
• data = file.read()
• print(data)
Read Mode
• Another way to read a file is to call a certain number of characters like
in the following code the interpreter will read the first five characters
of stored data and return it as a string:
• # Python code to illustrate read() mode character wise
file = open(“college.txt", "r")
print (file.read(5))
Read Mode
• We can also split lines while reading files in Python. The split()
function splits the variable when space is encountered. You can also
split using any characters as you wish.
• # Python code to illustrate split() function
with open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
Write Mode
• Creating a File using the write() Function
• In this example, we will see how the write mode and the write() function is
used to write in a file.
• The close() command terminates all the resources in use and frees the system
of this particular program.
• # Python code to create a file
file = open(‘college.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Write Mode
• We can also use the written statement along with the with() function.
• # Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")
Append Mode:
• # Python code to illustrate append() mode
file = open(‘college.txt', 'a')
file.write("This will add this line")
file.close()