Day11-String Methods # 2

Day11-String Methods # 2

Part # 02

METHODSMETHODSMETHODS
capitalizecountfind, index
upper, lowerendswith, startswithrfind, rindex
casefoldstrip, rstrip, lstripisupper, islower
centersplit, rsplit, splitness, joinisalnum, isalpha, isnumeric

Part # 02

capitalize ( ) :

It returns only the first character of the string to uppercase and the rest other characters of the string are turned to lowercase.

The string has no effect if the first character is already uppercase.

Example:

blogHeading = "introduction to python" 
#here 'introduction' 'i' is in lowercase converts into uppercase. 
print(blogHeading.capitalize) #output: Introduction to python

blogHeading2 = "introduction tO python" 
#here 'tO' 'O' is in uppercase converts into lowercase.
print(blogHeading2.capitalize) #output: Introduction to python

upper( ):

The upper() method converts a string to upper case/ capital alphabets.

lower( ):

The lower() method converts a string to lowercase / small alphabets.

Example:

a = "Python"
print(len(a))    #output: 5
print(a.upper()) #output: PYTHON
print(a.lower()) #output: python

casefold( ) :

The casefold() method - Returns a string where all the characters are lower case.

Example:

txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)  #output: hello, and welcome to my world!

center( ) :

The center() method aligns the string to the center as per the parameters given by the user.

str1 = "Welcome to the Console!!!"
print(len(str1)) #output: 25
print(str1.center(30)) #it adds 5 spaces before string
#output:  Welcome to the Console!!!

Note: The original length of string is 25 and the given requirement is 30. So 30-35=5. That's why it will add 5spaces before the string.

We can also provide padding character. It will fill the rest of the fill characters provided by the user.

Example:

str1 = "Welcome to the Console!!!"
print(str1.center(50, ".")) 
#output: ............Welcome to the Console!!!.............

count( ) :

The count() method returns the number of times the given value has occurred within the given string.

Example:

a = "Ali!! John Harry Ali" 
print(a.count("Ali")) #it counts how many times 'Ali' occur in string
#output: 2

endswith() :

It checks if the string ends with a given value. If yes then return True, else return False.

startswith( ) :

It checks if the string starts with a given value. If yes then return True, else return False.

Example:

  • endswith ( ):
a= "Welcome to the Console !!!"

#it tells that whether or not strings end with '!' 
print(a.endswith("!!!")) #output: True
x = "Welcome to the Console !!!"

#it tells that whether or not string b/w 4 and 10 index 
#i.e. "ome to" endswith 'to'
print(x.endswith("to", 4, 10))  #output: True
  • startswith ( ):
y = "Python is a Interpreted Language" 
print(y.startswith("Python")) #output: True

strip ( ) :

The strip() method removes any white spaces before and after the string means means it returns a trim version of the string.

rstrip() :

The rstrip() removes trailing characters (!!!) that are at the end of string means means it returns a right trim version of the string.

lstrip() :

The lstrip() method - removes trailing characters (!!!) that are at the start of string means it returns a left trim version of the string.

Example:

  • strip( ):
#Strip
a = " Silver Spoon "
print(a.strip) #output: Silver Spoon
  • rstrip( ):
#R-strip
x = "Python!!!"
print(x.rstrip("!"))  #output: Python

y = "!!Python!!!!" 
#it doesnot remove trailing characters that are at the start of string.
print(y.rstrip("!")) #output: !!Python
  • lstrip( ):
#L-strip
b = "!!Python!!!!" 
#it doesnot remove trailing characters that are at the end of string.
print(b.lstrip("!")) #Ouput: Python!!!!

split( ) :

This method splits the given string at the specified instance and returns the separated strings as 'list items'.

rsplit( ):

This method splits a string into a list, starting from the right. If no "max" is specified, this method will return the same as the split() method.

splitlines ( ):

This method splits a string into a list. The splitting is done at line breaks.

Example:

  • split( ):
a = "Hafsa John Harry" 
#here where is space present, it converts them into list
print(a.split(" ")) #output: ['Hafsa', 'John', 'Harry']
  • rsplit( ):
txt = "apple, banana, cherry"
x = txt.rsplit(", ")
print(x) #output: ['apple', 'banana', 'cherry']
txt = "apple, banana, cherry"  
x = txt.rsplit(", ", 1)
print(x)    #output: ['apple, banana', 'cherry']

Note: Here maxsplit =1, so it will return a list with 2 elements. Means the result has only 2 elements "apple, banana" is the first element, and "cherry" is the last.

  • splitness
txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines() #here \n does not came in return
print(x) #output: ['Thank you for the music', 'Welcome to the jungle']

txt = "Thank you for the music\nWelcome to the jungle"
y = txt.splitlines(True) #here \n cames in return
print(y)  #output: ['Thank you for the music\n', 'Welcome to the jungle']

join ( ):

This method takes all items in an iterable and joins them into one string.

A string must be specified as the separator.

Example:

myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x) #output: John#Peter#Vicky

myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x)  #output: nameTESTcountry

index() :

The index() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then raise an exception.

Example:

str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Dan"))
#output = 13

find ( ) :

The find() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then return -1.

Example:

str1 = "He's name is Dan. He is an honest man." 
print(str1.find("is")) #it tells index of where 'is' is present.
#output = 10

Note: As we can see, this method is somewhat similar to the index() method. The major difference being that index() raises an exception if value is absent whereas find() does not.

By using find method:

str1 = "He's name is Dan. He is an honest man."
print(str1.find("Daniel")) #if it doesnot find given string retrurn -1
#output = -1

By using index method:

str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel")) #if it doesnot find given string retrurn error
#output: ValueError: substring not found

rfind ( ):

  • The rfind() method finds the last occurrence of the specified value.

  • The rfind() method returns -1 if the value is not found.

  • The rfind() method is almost the same as the rindex().

Example:

txt = "Mi casa, su casa." 
x = txt.rfind("casa") #check last occurence of 'casa'
print(x)  #output: 12

txt = "Hello, welcome to my world."
y = txt.rfind("e", 5, 10) #index of 'e' between 5 and 10 index.
print(y) #output: 8

rindex ( ):

  • The rindex() method finds the last occurrence of the specified value.

  • The rindex() method raises an exception if the value is not found.

  • The rindex() method is almost the same as the rfind() method.

Example:

txt = "Mi casa, su casa."
x = txt.rindex("casa") #check last occurence of 'casa'
print(x) #output: 12

txt = "Hello, welcome to my world."
y = txt.rindex("e", 5, 10) #index of 'e' between 5 and 10 index.
print(y) #output: 8

isupper( ) :

It returns True if all the characters in the string are upper case, else it returns False.

islower( ):

It returns True if all the characters are in lower case, otherwise False.

Note: Numbers, symbols and spaces are not checked, only alphabet characters.

Example:

  • isupper( ):
str1 = "WORLD HEALTH ORGANIZATION" 
print(str1.isupper())  #output: True
  • islower( ):
a = "Hello world!"
b = "hello 123"
c = "mynameisPeter"

print(a.islower())  #output: False
print(b.islower())  #output: True
print(c.islower())  #output: False

isalnum ( ) :

It returns True only if the entire string only consists of A-Z, a-z, 0-9. If any other characters or punctuations are present, then it returns False.

Example:

str1 = "WelcomeToTheConsole"
print(str1.isalnum()) #output: True

isalpha( ) :

It returns True only if the entire string only consists of A-Z, a-z. If any other characters or punctuations or numbers(0-9) are present, then it returns False.

Example:

str1 = "Welcome"
print(str1.isalpha()) #output: True

str2 = "Welcome00"
print(str2.isalpha()) #output: False

isnumeric ( ):

It returns True if all the characters are numeric (0-9), otherwise False.

  • Exponents, like ² and ¾ are also considered to be numeric values.

  • "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not.

Example:

txt = "565543"
x = txt.isnumeric()
print(x)  #output: True

Continue....