Chapter 5 - Python Strings & String Methods
Chapter 5 - Python Strings & String Methods
>>>string_1 =“face”
>>>string_2 =“book”
>>>string_1+string_2
‘facebook’
When two strings are concatenated, there is no white space between them. If you need a white space
between the 2 strings, include a space after the first string or before the second string within the
quotes.
>>>singer = 50+”cent” gives an error as 50 is of integer type and cent is of string type.
>>>singer =str(50) + “cent”
>>>singer
‘50cent’
>>>repeated_str =“wow” * 5
>>>repeated_str
‘wowwowwowwowwow’
You can check the presence of a string in another string using in and not in membership operators
>>>fruit_str=“apple is a fruit”
>>>fruit_sub_str=‘apple’
>>>fruit_sub_str in fruit_string
True
>>> another_fruit_str=“orange”
>>>another_fruit_str not in fruit_str
True
3. String Comparison:
>, <, <=,>=,==, != can be used to compare two strings resulting in True or False. Python compares
the strings using ASCII value of the characters.
>>>”january” == “jane”
False
>>>”january” != “jane”
True
>>>”january” > “jane” # the ASCII value of u is more than e
True
>>>”january” < “jane”
False
>>>”january” >= “jane”
True
>>>”january” <= “jane”
False Built in functions Descriptions
>>>”filled”>”” Len() This function calculates the number
True of characters in a string
4. Built In Functions
using Strings Max() This function returns a character
There are built in functions for having highest ASCII value
which a string can be passed
Min() This function returns a character
as an argument.
having lowest ASCII value
Eg:
>>>max(“axel”)
‘x’
>>>min(“brad”)
‘a’
5. Accessing Characters in String by Index Number:
Each character in the string occupies a position in the string. Each of the string’s character
corresponds to an index number. First character is at index 0.
Syntax: string_name[index]
b e y o u r s e l f
index 0 1 2 3 4 5 6 7 8 9 10
>>>word_phrase=“be yourself”
>>>word_phrase[0]
‘b’
>>>word_phase[1]
e
>>>word_phase[2]
‘’
>>>word_phase[3]
y
The individual characters in a string can be accessed using negative indexing. If there is a long string
and you want to access end characters in a string, then you can count backwards from the end of
the string starting from the index of -1
>>>word_phrase[-1]
‘f’
>>>word_phrase[-2] b e y o u r s e l f
‘l’
index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
6. String Slicing and Joining
>>>drink[-3:-1] g r e e n t e a
‘te’
-9 -8 -7 -6 -5 -4 -3 -2 -1
>>>drink[6:-1]
‘te’ We can combine the positive and negative indexing numbers
Summary:
- Positive step: Requires `start < stop`.
- Negative step: Requires `start > stop`.
8. Joining Strings using Join() Method:
Strings can be joined with join() string. Join() method syntax is,
String_name.join(sequence)
If sequence is a string, then join() function inserts string_name between each item of list
sequence and returns the concatenated string.
>>>date_of_birth=[“17”,”09”,”1950”]
>>>”:”.join(date_of_birth)
‘17:09:1950’
>>>numbers=‘123’
>>>characters = ‘amy’
>>>password = numbers.join(characters)
>>>password
‘a123m123y’
The string value of ‘123’ is inserted between a and m and again between m and y and is assigned
to password string variable.
c) f-strings provide a concise, readable way to include the value of Python expressions inside
strings.
eg:
>>>f’The value is {value}’.
‘The value is 50.’
String Methods
String Methods in Python
• Python provides various in-built functions & methods that are
used for string handling. Those are
• lower() • find()
• upper() •index()
• replace() • isalnum()
• join() • isdigit()
• split() • isnumeric()
• islower()
• isupper()
String Methods in Python Cont..
☞ lower ():
• In python, lower() method returns all characters of given string in
lowercase.
Syntax:
str.lower()
Example: strlowerdemo.py Output:
str1="PyTHOn" python strlowerdemo.py
print(str1.lower()) python
☞ upper ():
• In python, upper() method returns all characters of given string in uppercase.
Syntax:
str.upper()
Example: strupperdemo.py Output:
str="PyTHOn" python strupperdemo.py
print(str.upper()) PYTHON
String Methods in Python Cont..
☞ replace()
• In python, replace() method replaces the old sequence of
characters with the new sequence.
Syntax: str.replace(old, new[, count])
Example: strreplacedemo.py
str = "Java is Object-Oriented and Java"
str2 = str.replace("Java","Python")
print("Old String: \n",str)
print("New String: \n",str2)
str3 = str.replace("Java","Python",1)
print("\n Old String: \n",str)
print("New String: \n",str3)
Output: python strreplacedemo.py
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Python
Old String: Java is Object-Oriented and Java
New String: Python is Object-Oriented and Java
String Methods in Python Cont..
☞ split():
• In python, split() method splits the string into a comma separated list.
The string splits according to the space if the delimiter is not provided.
Syntax: str.split([sep="delimiter"])
Example: strsplitdemo.py
str1 = “Java is a programming language"
str2 = str1.split()
print(str1);print(str2)
str1 = “Java,is,a,programming,language"
str2 = str1.split(sep=',')
print(str1);print(str2)
Output:
python strfinddemo.py
7 -1 12 7
String Methods in Python Cont..
☞ index():
• In python, index() method is same as the find() method except it returns
error on failure. This method returns index of first occurred substring
and an error if there is no match found.
Syntax: str. index(sub[, start[,end]])
Example: strindexdemo.py
str1 = "python is a programming language"
str2 = str1.index("is")
print(str2)
str3 = str1.index("p",5)
print(str3)
str4 = str1.index("i",5,25) Output:
print(str4) python strindexdemo.py
str5 = str1.index("java") 7
print(str5) 12
7
Substring not found
String Methods in Python Cont..
☞ isalnum():
• In python, isalnum() method checks whether the all characters of the
string is alphanumeric or not.
• A character which is either a letter or a number is known as
alphanumeric. It does not allow special chars even spaces.
Syntax: str.isalnum()
Example: straldemo.py
str1 = "python"
str2 = "python123" Output:
str3 = "12345" python straldemo.py
str4 = "python@123" True
str5 = "python 123" True
print(str1. isalnum()) True
print(str2. isalnum()) False
print(str3. isalnum()) False
print(str4. isalnum())
print(str5. isalnum())
String Methods in Python Cont..
☞ isdigit():
• In python, isdigit() method returns True if all the characters in the string
are digits. It returns False if no character is digit in the string.
Syntax: str.isdigit()
Example: strdigitdemo.py
str1 = "12345"
str2 = "python123"
Output:
str5 = "\u00B23" # 23 python strdigitldemo.py
str6 = "\u00BD" # ½ True
print(str1.isdigit()) False
print(str2.isdigit()) False
print(str5.isdigit()) False
print(str6.isdigit())
String Methods in Python Cont..
☞ isnumeric():
• In python, isnumeric() method checks whether all the characters of the
string are numeric characters or not. It returns True if all the characters
are numeric, otherwise returns False.
Syntax: str. isnumeric()
Example: strnumericdemo.py
str1 = "12345"
str2 = "python123"
Output:
python strnumericldemo.py
str5 = "\u00B23" # 23 True
str6 = "\u00BD" # 1/2
print(str1.isnumeric()) False
print(str2.isnumeric()) True
print(str5.isnumeric()) True
print(str6.isnumeric())
String Methods in Python Cont..
☞ islower():
• In python, islower() method returns True if all characters in the string
are in lowercase. It returns False if not in lowercase.
Syntax: str.islower()
Example: strlowerdemo.py
str1 = "python"
str2="PytHOn"
str3="python3.7.3"
print(str1.islower())
print(str2.islower())
Output:
print(str3.islower())
python strlowerldemo.py
True
False
3.islower()) True
String Methods in Python Cont..
☞ isupper():
• In python string isupper() method returns True if all characters in the
string are in uppercase. It returns False if not in uppercase.
Syntax: str.isupper()
Example: strupperdemo.py
str1 = "PYTHON"
str2="PytHOn"
str3="PYTHON 3.7.3"
print(str1.isupper())
print(str2.isupper())
Output:
print(str3.isupper())
python strupperldemo.py
True
False
True
String Methods in Python Cont..
☞ capitalize():
The capitalize() method returns a copy of the string with its first character
Capitalized and the rest lowercased.
Syntax: string_name.capitalize()
Eg: x="python programming"
y=x.capitalize()
print(y)
output: Python programming
☞ center():
The Method center() makes string _name centered by taking width parameter into
account. Padding is specified by parameter fillchar. Default filler is space.
Syntax: string_name.center(width[,fillchar])
String Methods in Python Cont..
Eg 1: x="python programming"
y=x.center(30)
print(y)
output: python programming
Eg 2: x="python programming"
y=x.center(30, “*”)
print(y)
print(len(y))
Output: ******python programming******
30
Width(30): This is the total width you want for the final string. It means the entire
string y will have a total of 30 characters (including the padding).
Fillchar(“*”): This is the character used for padding. It will fill the space on both sides
of the centered string.
String Methods in Python Cont..
☞ rjust():
In the method rjust(), when you provide the sting to the method rjust(), it returns the string right
justified.
Sy: string_name.rjust(width,[fillchar])
Ex1: x="python programming"
y=x.rjust(30,"*")
print(y)
Output: ************python programming
Width: The total length of the resulting string. If the width is smaller than the original string, no
padding is applied.
Fillchar: (Optional) The character used for padding. The default is a space.
text = "AI" Example with default padding:
result = text.rjust(5, '*') text = "AI"
print(result) result = text.rjust(5)
Output: ***AI print(result)
Output: " AI"
String Methods in Python Cont..
☞ ljust():
ljust() method is the opposite of rjust(). It left-aligns a string and pads it with a specified
character (default is a space) to make the string a certain width.
Syntax : string.ljust(width, fillchar)
Ex: Example with default padding
text = "AI"
text = "AI"
result = text.ljust(5, '*') result = text.ljust(5)
print(result) print(result)
Output: AI*** Output: "AI "
Width: The total length of the resulting string after padding. If the width is smaller than the
original string, no padding is added.
Fillchar: (Optional) The character used for padding. By default, it is a space.
String Methods in Python Cont..
☞ endswith():
endswith() method is used to check if a string ends with a specified suffix (or multiple
suffixes). It returns True if the string ends with the suffix, otherwise it returns False.
Syntax: string.endswith(suffix[, start[, end]])
Suffix: The string (or tuple of strings) to check at the end of the string.
Start: (Optional) The position in the string where the search starts. Defaults to the
beginning of the string (index 0).
End: (Optional) The position where the search ends. Defaults to the end of the string.
Ex 1 :
Example 2: Using multiple suffixes (tuple)
text = "machine_learning"
result = text.endswith("learning") text = "data_analysis.py"
l print(result) result = text.endswith((".py", ".txt"))
print(result)
Output: True
Output: True
String Methods in Python Cont..
x="this is apple"
y=x.endswith("apple",0,6)
print(y)
Output: False
y=x.endswith("apple",4,13)
print(y)
True
y=x.endswith(("apple","apples"),2,13)
print(y)
True
String Methods in Python Cont..
☞ startswith():
Startswith() method checks if a string starts with a specified prefix (or multiple prefixes). It
returns True if the string starts with the specified prefix, otherwise it returns false,
Syntax: string.startswith(prefix[, start[, end]])
Prefix: The string (or a tuple of strings) to check at the start of the string.
Start: (Optional) The position in the string where the search starts. Defaults to 0 (the beginning of
the string).
End: (Optional) The position where the search ends. Defaults to the end of the string.
Example 1: Basic usage Example 2: Using multiple prefixes (tuple)
text = "deep_learning_model"
result = text.startswith("learning", 5, 15)
print(result)
Output: True
☞ count():
The count() method in Python is used to count the number of occurrences of a substring
within a string.
Syntax: string.count(substring, start=, end=)
Substring: The string whose occurrences you want to count.
Start (optional): The index where the search starts.
end(optional): The index where the search ends.
String Methods in Python Cont..