12 Lecture Python Strings - Part 2
12 Lecture Python Strings - Part 2
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=“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:”
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:”
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:”
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”
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
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
new_animal = “Bear”
print(animal == new_animal) #=> True
print(animal is new_animal) #=> True
What Will be the Output?