Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

12 Lecture Python Strings - Part 2

The document discusses various string methods and operators in Python, including comparing strings for equality, finding substrings within strings, splitting strings into lists, and parsing strings to extract data like IP addresses. It provides examples of using string methods like find, split, isnumeric, and slicing to manipulate and analyze string data. The document also covers the difference between calling methods versus functions and checking if strings contain only numbers or start with capital letters.

Uploaded by

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

12 Lecture Python Strings - Part 2

The document discusses various string methods and operators in Python, including comparing strings for equality, finding substrings within strings, splitting strings into lists, and parsing strings to extract data like IP addresses. It provides examples of using string methods like find, split, isnumeric, and slicing to manipulate and analyze string data. The document also covers the difference between calling methods versus functions and checking if strings contain only numbers or start with capital letters.

Uploaded by

wh14257
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

PYTHON Programming (CST310)

Lecture 12: String Data Type- Part 2

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 04, 2023
String comparison in Python

• The comparison operators work on strings.


• To see if two strings are equal, we will use Equal to (==) operator.
a=“demo”
b=“demo”
c=“Demo”
print(a==b) #produces True if string in a and b are equal
print(a==c) #produces False, if a and c are not equal.
id(a)
id(b)
id(c) #in the above example, id of a and b will be equal,
while, id of c will be different from a and b.
String comparison
• Other comparison operators for strings.
name1=‘Abhishek’
name2=‘Anurag’
name1 < name2 # what will be the output? Error? Or True or False?

In comparison of Strings, the characters of both the strings are compared one by one.
When different characters are found, their Unicode value is compared.
The character with lower Unicode value is considered to be smaller.

• Python does not handle uppercase and lowercase letters the same way that people do.
• All the uppercase letters come before all the lowercase letters
a=“abhishek”
b=“Prince”
a>b
Method vs Functions
• Calling a method is similar to calling a function (it takes arguments and
returns a value) but the syntax is different.
• We call a method by appending the method name to the variable name
using the period as a delimiter
• For example:
s.lower() # method calling syntax
lower(s) #function calling syntax
Some useful Functions and Methods for
Strings
s=“NIT Srinagar”
1. type(s): returns the data type of variable s
2. dir(s): lists all the methods that can be applied on variable s of type
String.
3. help(str.function_name): gives the description of a method
4. s.startswith(‘NIT’): checks if the string starts with ‘NIT’ or not.
Split method in Python
Split method breaks the given string into Substrings using space
(default) as separator and put the substrings as elements in a list.

S=“NIT SRINAGAR is in Srinagar”


S.split()

#S.split will return the following list


[“NIT”, “SRINAGAR”, “is”, “in”, “Srinagar”]
find method in Python
Find method finds if a substring is in the given string or not.
If the string is present, it returns the starting index of that substring in the given
string.
If substring not found, then it returns -1

S=“Prabhdeep”
S.find(“deep”) # this will return the starting index of “deep”

S=“Singh1 Singh2”
s.find(“Singh”) # this will return the starting index of first occurrence of Singh
s.find(“Singh”, 7) # here we are searching the keyword from the 7th index.
index method in Python
Index method works same like the find method.
Difference is incase of substring not found, Index method generates an
Error(Value not found)
Check if a string contains only numbers
isnumeric() returns True if all characters are numeric.

“20030”.isnumeric()
'1.0'.isnumeric()
String Parsing
s=“Pinging google.com [172.217.167.206] with 32 bytes of data:”

s1=“Pinging google.com [1.1.1.1] with 32 bytes of data:”

Suppose, our requirement is to fetch the substring IP address from the


above String. How we can do it?

Hint: We will use the Slicing Concept


Possible Solution for Previous Problem
s=“Pinging google.com [172.217.167.206] with 32 bytes of data:”

Suppose, our requirement is to fetch the substring IP address from the


above String. How we can do it?

s[s.find("[")+1:s.find("]")]
or
s[s.index("[")+1:s.index("]")]
Problem 2:
s=“Pinging google.com @172.217.167.206 w 32 bytes of data:”

s2=“Pinging www.google.com @172.217.167.206 w 32 bytes of data:”

Suppose, our requirement is to fetch the IP address from the above String.
How we can do it?
Possible Solution to Previous Problem
s=“Pinging google.com @172.217.167.206 with 32 bytes of data:”

Suppose, our requirement is to fetch the IP address from the above


String. How we can do it?

s[s.find("@")+1:s.find("w")-1]
or
s[s.find("@")+1:s.find(" ",s.find("@"))]
Practice Program
s= “Reply from 117.203.246.106: bytes=32 time=90ms TTL=48”

Fetch the ip address from the above given string.


Possible Solution
s= “Reply from 117.203.246.106: bytes=32 time=90ms TTL=48”

Split_in_list= s.split() # split will split the above string into


substring with whitespace as separator
and save the strings in a list
for item in splitted_list:
if item.find(“.”)!=-1:
print(item)
Practice Problem
Take the following Python code that stores a string:
str = ’X-DSPAM-Confidence:0.8475’

Use find and string slicing to extract the portion of the string after the
colon character and then use the float function to convert the
extracted string into a floating point number.
Program to find the IP address of a Website
(using Ping in cmd)
import subprocess

url=input("enter the website name")

output=subprocess.check_output(["ping",url],shell=True)

s=str(output)

print(s[s.find("[")+1:s.find("]"):])
What Will be the Output?

animal = “Bear”
more_animal = animal

print(animal == more_animal) # == checks only the equality


print(animal is more_animal) # is operator checks the id(memory location)

new_animal = “Bear”
print(animal == new_animal) #=> True
print(animal is new_animal) #=> True
What Will be the Output?

animals = “Bear panda”


few_more_animals = animals

print(animals == few_more_animals) # == checks only the equality


print(animals is few_more_animals) # is operator checks the id(memory location)

even_more_animals = “Bear Panda”


print(animals == even_more_animals) #=> True
print(animals is even_more_animals) #=> False
To check if each word in a string begins with a
capital letter?
The istitle() function checks if each word in a given string is capitalized.

print(“Aman”.istitle()) # returns True


print(“abhishek”.istitle()) #returns False
Print(“Vivek is”.istitle()) #returns False
print(“Usaid Cse”.istitle()) #returns True

You might also like