string and string methods in python programming

string and string methods in python programming



 mystr="i am very Cool"

print(mystr) #this prints string as it is
print(mystr[5]) #this prints 5th character of mystr string
print(mystr[10]) #this prints 10th character of mystr string

#slicing
print(mystr[0:6]) #prints slice of string mystr from index 0 to 6
print(mystr[2:9]) #prints slice of string mystr from index 2 to 9

print(len(mystr)) #returns the length of string

#slicing with counter
print(mystr[::2]) #prints slice of string with leaving every 2nd character
print(mystr[::3]) #prints slice of string with leaving every 3nd character

#negative index (counts string from backward)
print(mystr[-1]) #prints -1 index number character

#reversing string using negative index (-1)
print(mystr[::-1]) #print string characters in backwards
print(mystr[::-2]) #print string characters in backwards with leaving every 2nd character

#string functions
print(mystr.capitalize()) #capitalize first character of the string
print(mystr.casefold()) #convert the whole string into lower case
print(mystr.count("o")) #returns the number of times the character of given value is appeared in string
print(mystr.encode())#returns the utf-8 encoded version of string
print(mystr.endswith("ol"))#returns true if the string ends with given value
print(mystr.upper()) #convert all the characters of string into upper case
print(mystr.swapcase()) #convert lower to upper case and vice versa
print(mystr.replace("Cool","hot")) #replace the 'Cool' pattern with 'hot' in string
print(mystr.find("Cool"))#finds the given value in string and return starting index of value

Comments