0% found this document useful (0 votes)
604 views

Python Strings

The document discusses strings and file handling in Python. It covers: 1) What strings are and how they are defined in Python using single or double quotes. 2) Details about strings being immutable sequences of characters that can contain letters, numbers, and special characters. 3) Different ways of creating strings in Python using single quotes, double quotes, triple quotes, string interpolation and formatting.

Uploaded by

mahendra naik
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
604 views

Python Strings

The document discusses strings and file handling in Python. It covers: 1) What strings are and how they are defined in Python using single or double quotes. 2) Details about strings being immutable sequences of characters that can contain letters, numbers, and special characters. 3) Different ways of creating strings in Python using single quotes, double quotes, triple quotes, string interpolation and formatting.

Uploaded by

mahendra naik
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Strings and File Handling

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"

# create a string using single quotes


string1 = 'Python programming‘
• Here, we have created a string variable named string1. The variable is
initialized with the string Python Programming.
Strings
• A string in Python is an ordered sequence of characters enclosed
within single or double quotes.
• It can contain letters, numbers, special characters, and even escape
sequences.
•  Strings are immutable in Python, meaning their values cannot be
changed after they are created.
• Strings are used widely in many different applications, such as storing
and manipulating text data, representing names, addresses, and other
types of data that can be represented as text.
Creating String in Python
• There are different ways, we can create strings in Python:
• Create a string in Python using Single quotes:
• You can use single quotes to define a string that contains characters,
digits, and special symbols.
• Example:
stringName=‘New Horizon College of Engineering'
print(stringName)
Creating String in Python
• Multi-Line Strings with Single Quotes:
• Example:
stringMultiline = 'This is a multi-line string using \
single quotes. It works by adding an escape \
character at the end of each line.'
print(stringMultiline)
Creating String in Python
• String Interpolation with Single Quotes: You can also use single quotes
when performing string interpolation using f-strings or the str.format()
method:
College_name = ‘New Horizon college of Engineering'
place = “Bengaluru”
f_string = f'{college_name} is in {place}.'
format_string = '{college_name} is in {place}.'.format(college_name,place)
print(f_string)
print(format_string)
Creating String in Python
• Create a string in Python using double quotes
• Example:
string1 = "New Horizon college of Engineering"
print(string1)
Creating String in Python
• Strings with Single Quotes: When your string contains single quotes, you can use
double quotes to avoid the need for escaping:
string2 = "It's always fun to learn python”
print(string2)

Escaping Double Quotes within Double-Quoted Strings:


• If your Python string contains double quotes, you’ll need to escape them using a
backslash (\). Without the escape character, the interpreter would assume that the
double quote marks the end of the string:
string3 = "The \"City of Angels\": Los Angeles, California"
print(string3)
Creating String in Python
• Multi-Line Strings with Double Quotes:
string5 = "Famous US cities include: \
\"New York City, New York\", \
\"Los Angeles, California\", and \
\"Chicago, Illinois\"."
print(string5)
Creating String in Python
• Create a string in Python using triple quotes(‘” “‘)
• Triple quotes in Python allow you to create strings that span multiple lines or contain both single and
double quotes. You can use triple single quotes (''' ''') or triple double quotes (""" """).
• Here are two examples featuring various city names from the United States of America:
• Example:
stringMultiline = """Some popular cities in the United States of America:
- New York City, New York
- Los Angeles, California
- Chicago, Illinois
- Houston, Texas
- Phoenix, Arizona
""“
print(stringMultiline)
Creating String in Python
• Example-2: String with Both Single and Double Quotes:
string2 = '''Famous nicknames of American cities:
- "The Big Apple" - New York City
- "The Windy City" - Chicago
- "The City of Angels" - Los Angeles
- "The City by the Bay" - San Francisco
- "America's Finest City" - San Diego
'''
print(string2)
Accessing and Modifying String Values:
• Once you’ve declared a variable and assigned it to a string, you can
access individual characters in the string using indexing or slicing.
• Keep in mind that strings in Python are immutable, which means
their values cannot be changed.
• However, you can create new strings using existing ones.
Accessing characters in Python String
• In Python, individual characters of a String can be accessed by using
the method of Indexing.
• Indexing allows negative address references to access characters from
the back of the String, e.g. -1 refers to the last character, -2 refers to
the second last character, and so on.
• While accessing an index out of the range will cause an IndexError.
• Only Integers are allowed to be passed as an index, float or other
types that will cause a TypeError.
Accessing characters in Python String
• # Python Program to Access
# characters of String
String1 = “New Horizon College of Engineering"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
Reversing a Python String
• With Accessing Characters from a string, we can also reverse them.
• We can Reverse a string by writing [::-1] and the string will be
reversed.
• #Program to reverse a string
college = “New Horizon college of Engineering"
print(college[::-1])
Reversing a Python String
• We can also reverse a string by using built-in join and reversed
function.
• # Program to reverse a string
college = “New Horizon college of Engineering"
# Reverse the string using reversed and join function
college_reversed = "".join(reversed(college))
print(college_reversed)
String Slicing
• To access a range of characters in the String, the method of slicing is used.
• Slicing in a String is done by using a Slicing operator (colon).
• # Python Program to demonstrate String slicing
# Creating a String
String1 = “New Horizon college of Engineering"
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between 3rd and 2nd last character
print(“\nSlicing characters between” + “3rd and 2nd last character:” )
print(String1[3:-2])
Python String split() Method

• 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.

strip() Used to trim whitespaces from the string object.

upper() We can convert a string to uppercase in Python using str.upper() function.

lower() This function creates a new string in lowercase.

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()

You might also like