String Stringmethod
String Stringmethod
STRING:
A String is a sequence of characters enclosed within single quotes or double quotes or three single quotes/three double quote s.
Syntax to create the string:
Variable_name = 'collection_of_characters' OR
Variable_name = "collection_of_characters" OR
Variable1_name = '''collection_of_characters''' / """collection_of_characters"""
• If string is created b/w 3 pair of single quote is called as doc string/paragraph string.
• If string is started with single quote then we need to end with single quote itself and same for other two.
• If single quote (')is present in a string then " " has to be used.
Ex: 'welcome to python's world' error
"welcome to python's world"
• We have len() built in function to find the length of the collection or object or variable or string.
Raw string:
• Python raw string are the string are the string literals prefixed with "r" or "R"
• Raw string do not treat backslashes as a part of an escape sequence. If will be printed normally as a string
MAIN FRAME
b
0x31 0x34
Slicing a string:
• Process of extracting multiple characters at a time /simultaneously.
• Syntax : var_name[start index : end index : step value]
Start index : default value (o)[optional]
End index : default value (-length of the string)[optional]
Step value : default value (1)[optional]
• Note : Element at the end index will not be added in the slicing.
Ex :
message = 'Hello world'
0 1 2 3 4 5 6 7 8 9 10
H e l l o w o r l d
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
message[:5] 'Hello'
message[6:] 'world'
message[0:-6] 'Hello'
message[2:-3] 'llo wo'
message[-9:-3] 'llo wo'
message[::2] 'Hlowrd'
message[::-2] 'drwolh'
message[::-1] 'dlrow olleh'
String formatting :
• Infusing data dynamically into a string during the time of execution or runtime is called formatting.
• There are 3 ways of string formatting:
• Formatting with placeholders.
• Formatting with .format() string method
• Formatting with string literals called f-string
capitalize () : python strings capitalize () function returns the first letter of the string in the capital form.
Ex : my_message = 'good morning'
my_message.capitalize() 'Good morning'
upper () : python string upper () returns all the alphabet characters to uppercase.(we can have numbers and special character in string).
Ex : my_message = 'good morning'
my_message.upper() 'GOOD MORNING'
lower () : python string lower () returns all the alphabet characters to lowercase.(we can have numbers and special character in string).
Ex : my_message = 'Good Morning'
my_message.lower() 'good morning'
swapcase () : python string Swapcase () returns new string which convert uppercase to lowercase and vice-versa.
Ex : my_message = 'Good Morning'
my_message.swapcase() gOOD mORNING
count () : python string count () returns the number of occurrence of the specific substring inside the given string.
Ex : my_message = 'good morning'
my_message.count('n') 2
my_message = "Hello world, Hello universe"
print(my_message.count(‘l’)) 5 # Prints number of occurrences of the letter ‘l’
print(my_message.count('Hello', 0, 1 # Prints number of occurrences of the word 'Hello' between the indices 0 and
10)) 10
index () : python string index () returns the lowest index where the specified substring is found. OR
•Searches the string for a specified value and returns the position of where it was found
•finds the first occurrence of the specified value.
•returns valueError if the value is not found.
•Syntax:
Syntax : str.index('substring',[startindex],[ endindex])
rindex() : Searches the string for a specified value and returns the last position of where it was found
Eg : my_message = "Hello World"
1. print(my_message.index('l’)) 2 # Prints the index of first occurence of the letter 'I'
2. print(my_message.rindex("l’)) 9 # Prints the index of last occurence of the letter’l’
3. print(my_message.index('Universe’)) ValueError
my_message = 'good morning'
my_message.index('m') 5
find () : python string find () is used to find the index of a substring in a string. OR
• Searches the string for a specified value and returns the position of where it was found
• finds the first occurrence of the specified value.
• returns -1 if the value is not found.
• Syntax: string.find(value, [start], [end])
rfind() : Searches the string for a specified value and returns the last position of where it was found
Eg : my_message = "Hello World"
1. print(my_message.find('I’)) 2 # Prints the index of first occurence of the letter 'I’
2. print(my_message.rfind('I’)) 9 # Prints the index of last occurence of the letter 'I'
3. print(my_message.find('Universe’)) -1
4. print("today is beautiful day".rfind("day")) 19
5. print("today is beautiful day".find("day")) 2
replace () : python string replace () is used to create a new string by replacing some parts of another string. OR
• Replaces a specified phrase with another specified phrase.
• Syntax: string.replace(oldvalue, newvalue, [count])
Eg:
"Malayalam".replace("a", "q") "Mqlqyqlqm"
"Hello World".replace("World", "Universe") "Hello Universe“
startswith () : python strings Startswith () function returns True if the string starts with the given specified value, otherwise it returns
False.
• Syntax: string.startswith(value, [start], [end])
Eg:
"how are you".startswith("are") False
endswith () : python strings endswith () function returns True if the string ends with the given specified value, otherwise it returns False.
• Syntax: string.endswith(value, [start], [end])
Eg:
"how are you".endswith("you") True
split () : python string split () is used to split a string into list of string based on the delimiter. OR
• Splits the string at the specified separator, and returns a list.
• syntax: string.split([separator], [maxsplit])
rsplit() 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().
• Converts a string into a list.
Eg:
'This is my string'.split('s’) ['Thi', 'i', ' my', 'tring']
"This is my string".split() ['This', 'is', 'my', 'string']
"This is my string".split(" ",2) ['This', 'is', 'my string']
"This is my string".rsplit(" ",2) ['This is', 'my', 'string]
join() : Joins the elements of an sequence using the string specified. OR Syntax: string.join(iterable)
• Converting other data type into a string.
Eg : data = "hai"
data.join(["hello", "world"]) "hellohaiworld"
message = 'hello'
'-'.join(message) "h-e-l-l-o“ # Joins each character of the string using '-'
','.join(message) “h,e,l,l,o” # Joins each character of the string using ','
strip() : removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to
remove)
Syntax: string.strip()
rstrip():removes any trailing characters
Syntax: string.rstrip ()
lstrip():A removes any leading characters
Syntax: string.Istrip()
Note: All string methods returns new values. They do not change the original string.
Concatenation :
It is the process of combination two or more strings by using plus(+) operator.
Syntax : str1 + str2
Ex : s1 = 'hello'
s2 = 'world'
Print(s1+s2) 'helloworld'
a = 'hai'
b = 'hello'
c = 'good'
d= 'morning'
Print(a+b+c+d) 'haihellogoodmorning
Print(a+' '+b+' '+c+' '+d) 'hai hello good morning
Replication :
It is a process of creating some copies of given string using asterisk(*) operator.
It returns specified number of duplicate specified strings.
Syntax : str * int
Ex : s = 'hello'
s*5 'hellohellohellohellohello
S = '67'
s*4 '67676767'