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

12 Lecture 12 Python Strings

Here are the ways to print the above statements in Python: 1. Using Triple Quotes: print("""Hello "Boss". How are you""") 2. Using Escape Character: print('He said, \"What\'s there?\"') The triple quotes allow embedding of the quote character inside the string without escaping it. The escape character \ is used to escape the quote character inside the string.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

12 Lecture 12 Python Strings

Here are the ways to print the above statements in Python: 1. Using Triple Quotes: print("""Hello "Boss". How are you""") 2. Using Escape Character: print('He said, \"What\'s there?\"') The triple quotes allow embedding of the quote character inside the string without escaping it. The escape character \ is used to escape the quote character inside the string.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

PYTHON Programming (CST310)

Lecture 12: Strings in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 01, 2022
Strings in Python
• Strings in Python can be created by enclosing characters in quotes.
• Python treats single quotes the same as double quotes.
• Creating strings is as simple as assigning a value to a variable.
name=“nit Srinagar”
city=‘Srinagar’
Accessing Values in Strings
• Python does not support a character data type
• 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.
• To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring.
• Like other languages, the indexing of the Python strings starts from 0.
• For example − Accessing Individual Characters in Strings

msg1 = ‘NIT Srinagar’


print(msg1[0])
print(msg1[1])
print(msg1[2])
print(msg1[3])
print(msg1[16]) # This will give error. Because 16th index doesn’t
exist
Accessing Individual Characters in Strings
msg1 = ‘NIT Srinagar’

for i in msg1:
print(i)

or
for i in range(0,len(msg1)):
print(msg1[i])
Accessing Substrings in Strings
• The slice operator or square brackets [] is used to access the individual characters
of the string.
• However, we can use the : (colon) operator in Python to access the substring from
the given string.
string[start:end:step]
where,
start: The starting index of the substring. The character at this index is
included in the substring. If start is not included, it is assumed to equal to 0.
end: The terminating index of the substring. The character at this index is not
included in the substring. If end is not included, or if the specified value
exceeds the string length, it is assumed to be equal to the length of the
string by default.
step: Every "step" character after the current character to be included. The
default value is 1. If step is not included, it is assumed to be equal to 1.
Accessing Substrings in Strings
string[start:end] Get all characters from start to end – 1
string[:end] Get all characters from the beginning of the string to end - 1

string[start:] Get all characters from start to the end of the string

string[start:end:step] Get all characters from start to end - 1, not including


every step character

Note:
The start or end index can be a negative number.
A negative index means that you start counting from the end of the string
instead of the beginning (from the right to left).
Accessing Substrings in Strings
msg2= "Python Programming“
msg2[1:5] #this will give substring starting from index 1 to (5-1)

msg2[:] #this will give the whole original string


msg2[0:] #this will give the whole original string
msg2[:len(msg2)] #this will give the whole original string
msg2[:4] # this will give substring starting from index 0 to (4-1)
msg2[:-1] #this will print complete string except the last character
msg2[:-2] #this will print complete string except the last two characters
msg2[: - len(msg2)] #this will an empty string
msg2[-1:] #this will print the last character
msg2[-2:] #this will print the last two characters
Problems:
n=“Jammu and Kashmir”
n[2:4]
n[:3]
n[:-3]
n[-2:]
Practice Problems
string = “NIT Srinagar 2019"

1. #Print First 5 Characters


print(string[0:5])
2. Get a substring 4 characters long, starting from the 3rd character of the string
print(string[3:7])
3. Get the last character of the string
print(string[-1:]
4. Get the last 5 characters of a string
print(string[-5:])
5. Get a substring which contains all characters except the last 4 characters and the 1st
character
print(string[1:-4])
6. Reverse of String
string[len(string):0:-1]
Strings are immutable in Python.
• The string cannot be modified.
• 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.
say if s=“NIT Srinagar”
i.e. s[0]="s“ is not allowed.
However, s=“Kashmir” will work.
But, here also modification was not done on the original string. Here,
now the s is pointing to a new object with value “Kashmir”
Deleting the String
• As we know that strings are immutable.
• We cannot delete or remove the characters from the string.
• But we can delete the entire string using the del keyword.

s=“NIT SRINAGAR”
del s will delete the string object “NIT Srinagar”
print(s) # will give error

We cannot delete individual characters of string. i.e. del s[0] will not work
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 an element from a particular string.
It is known as range slice operator. It is used to access the substring from the specified
[:]
range.
It is known as membership operator. It returns if a particular sub-string is present in the
in
specified string.
It is also a membership operator and does the exact reverse of in. It returns true if a
not in
particular substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to
r/R 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.
String Methods
• A method is like a function, but it runs "on" an object.
Suppose s=“NiT Srinagar”
1. s.lower(): returns the lowercase version of the string
2. s.upper(): returns the uppercase version of the string
3. s.split(): method splits a string into a list by using whitespace as
separator. For example: s.split will return a list with two strings
“NIT” and “Srinagar”. We can split the strings using some other
separator also.
s.split(‘a’)
String Methods
4. s.count(): Returns the number of times a specified value occurs
in a string
5. s.find(“nit”): searches for the given string “nit” (not a regular
expression) within s, and returns the first index where it begins or -1 if
not found
6. s.replace('old', 'new') -- returns a string where all occurrences of
'old' have been replaced by 'new'
S=“NIT Srinagar”

• WAP to count the total occurrence of a character/substring in a string.


• WAP to reverse a string using slicing operator
• WAP to reverse a string using loops
• WAP to reverse a string using Recursion
Python String Formatting
How to print the following statements in python:
1. Hello “Boss”. How are you
2. He said, "What's there?“

One way is making use of Triple Quotes


And other is making use of Escape characters.

You might also like