0% found this document useful (0 votes)
3 views

Chapter 5 - Python Strings & String Methods

The document provides a comprehensive overview of string manipulation in Python, covering string creation, basic operations, comparisons, slicing, and built-in methods. It explains how to join and split strings, the immutability of strings, and various string formatting techniques. Additionally, it distinguishes between the isdigit() and isnumeric() methods and lists common string methods available in Python.

Uploaded by

rahmathb1612
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 5 - Python Strings & String Methods

The document provides a comprehensive overview of string manipulation in Python, covering string creation, basic operations, comparisons, slicing, and built-in methods. It explains how to join and split strings, the immutability of strings, and various string formatting techniques. Additionally, it distinguishes between the isdigit() and isnumeric() methods and lists common string methods available in Python.

Uploaded by

rahmathb1612
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Strings

Creating and Sorting Strings:

Strings consist of one or more characters surrounded by matching quotation marks.


Strings are surrounded by either
• Single or double quotation marks.
• A string enclosed in double quotation marks can contain single quotation marks and vice
versa.
• If you have a string spanning multiple lines, than it can be included within triple quotes.
• You can find the type of a variable by passing it as an argument to type() function.
• Python strings are of str data type.

1. The str() Function:


• Str() function returns a string and the syntax for str() function is str(object).
• It returns a string version of the object.
• >>> str(10)
• ‘10’
• >>>create_string=str()
• >>>type(create_string)
• <class ‘str’>
• Here integer 10 is converted to string. The create_string is an empty string of type str.
2. Basic String Operations:
In Python, strings can also be concatenated using + sign and * operator is used to create a repeated
sequence of strings

>>>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

The syntax for string slicing is,


String_name[start:end[:step]]
You can access a sequence of characters by specifying a range of index numbers separated by a colon.
The string slicing starts from the beginning and extending up to but not including end. After slicing
substring is created.
>>>drink =“green tea”
>>>drink[0:3]
‘gre’
>>>drink[:5]
‘green’
>>>drink[6:]
g r e e n t e a
‘tea’ 0 1 2 3 4 5 6 7 8
>>>drink[:]
‘green tea’
>>>drink[6:20]
‘tea’
A substring is a sequence of characters contained in a string.
If start index and end index are omitted, then the entire string is displayed
If the start index is equal to or higher than end index, result is an empty string.
Slicing can be done using negative integer numbers.

>>>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

7. Specifying steps in Slice Operation:


Steps refers to the number of characters that can be skipped after the start indexing character in
the string. Default value of step is one.
>>>newspaper=“new York times”
>>>newspaper[0:13:4]
‘ny e’
>>>newspaper[::4]
‘ny e’
Starts with index 0 and till n and will print every 4th character.
Note:
When the start index is greater than the stop index, it is only applicable when using a
negative step. This works for both positive and negative indexing.
Behaviour based on step:
1. Positive step (`step > 0`):
- The slice will start at the `start` index and proceed forward towards the `stop` index. If
the `start` index is greater than the `stop` index, the result will be an empty string because
Python expects to move forward, but it can't.
drink = "green tea"
print(drink[6:3:1])
Output: ‘ ’ (empty string, because start > stop and step is positive)
2. Negative step (`step < 0`):
- The slice will start at the `start` index and proceed backwards toward the `stop` index.
Here, the `start` index should be greater than the `stop` index to retrieve characters.
drink = "green tea"
print(drink[6:3:-1])
Output: 'ter’ (it slices backward from index 6 to index 4)

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.

9. Split Strings using split() Method:


The syntax is
string_name.split([separator [, maxsplit]])
If the seperator is not specified, then whitespace is considered as the delimiter string.
9. Split Strings using split() Method:
In Python, the `split()` method is used to divide a string into a list of substrings
based on a specified delimiter (separator). By default, if no separator is provided,
`split()` will use any whitespace (spaces, tabs, or newlines) to split the string.
Syntax: string.split(separator, maxsplit)
separator (optional): Specifies the delimiter string on which to split the string. If
omitted, any whitespace is used.
maxsplit (optional): Defines the maximum number of splits to do. The default
value is `-1`, meaning no limit (i.e., split at every occurrence of the separator).
Note: the split() method in Python can only be applied to strings. It is
designed to divide a string into a list of substrings based on a specified delimiter.
Data Type:`split()` works exclusively on string objects.
- If you try to call `split()` on non-string data types, like integers or lists, you will
get an `AttributeError` because those data types do not have a `split()` method.
Examples:
1.Basic Example (Default Behavior -Whitespace Separator):
text = "Python is easy to learn"
words = text.split() # Split by whitespace (spaces)
print(words)
Output: ['Python', 'is', 'easy', 'to', 'learn’]
2. Using a Custom Separator:
text = "apple,banana,cherry"
fruits = text.split(",") # Split by comma
print(fruits)
Output: ['apple', 'banana', 'cherry’]
3. Limiting the Number of Splits (Using “maxsplit”):
text = "one two three four five"
limited = text.split(" ", 2) # Split by space, but only 2 splits
print(limited)
Output: ['one', 'two', 'three four five']
Using split() on integer
num = 12345
num.split() # This will raise an AttributeError
Output: AttributeError: 'int' object has no attribute 'split’
Using split() on list
lst = [1, 2, 3]
lst.split() # This will also raise an AttributeError
Output: AttributeError: 'list' object has no attribute 'split’

Passing single string


x = "goodmorning"
y = x.split()
print(y)
Output: ['goodmorning’] #since “goodmorning” doesn't contain any spaces or
separators, the entire string is treated as a single word. As a result, the string is
not split, and it remains as [‘goodmorning’]
To split the word into individual characters:
Example 1: Using list()
x = "goodmorning"
y = list(x)
print(y)
Output: ['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g']
Example 2: Using a List Comprehension:
x = "goodmorning"
y = [char for char in x]
print(y)
Output: ['g', 'o', 'o', 'd', 'm', 'o', 'r', 'n', 'i', 'n', 'g']
Eg:
>>>shoes = “ Nike Puma Adidas Bata Liberty”
>>>shoes.split()
>>>icecream=“vanilla, black current, strawberry, chocolate”
>>>icecream.split(“,”)
The string icrecream is split with the seperator as ,. If seperator is not specified, whitespace is
used by default.
10. Strings are immutable:
The characters in a string cannot be changed once it is assigned to string variable.
>>>stringVar = “Hello”
>>>stringVar[0] = “c” // this line gives an typeerror saying str object does not support item
assignment
11. String Traversing:
Each of the characters in a string can be traversed using the for loop.
Eg:
def main():
stringVar = “KLESNC”
index = 0
for each_character in stringVar:
print(f”Character ‘{each_character}’ has an index value of {index}”)
index+=1
Strings are immutable
12: String Methods
All the methods supported by string can be found using the dir command.
>>>dir(str)
COPY METHODS from TEXT Book
what is the difference between isdigit() and isnumeric() python
isdigit():
• The isdigit() method returns ‘True’ if all characters in the string are digits, and the
string is not empty.
• It does not consider other numeric characters such as superscripts and subscripts.
• It is specific to ASCII digits (0-9).
>>>text = "12345"
>>>result = text.isdigit()
>>>print(result) # Output: True
isnumeric():
The isnumeric() method returns ‘True’ if all characters in the string are numeric
characters, including digits, superscripts, subscripts, and more.
It is a more general method compared to isdigit()
>>>text = "12345“
>>>result = text.isnumeric()
>>>print(result) # Output: True
• In summary, isdigit() is more restrictive and checks only for
ASCII digits, while isnumeric() is more inclusive and
considers a broader range of numeric characters.
Depending on your use case, you might choose one over the
other. If you specifically want to check for digit characters
(0-9), isdigit() is often more appropriate. If you want to
check for a broader set of numeric characters, including
superscripts and subscripts, then isnumeric() may be more
suitable.
13. Formatting Strings:
The strings can be formatted in the below ways:
a) %-formatting : Only str, int and doubles can be formatted. All other types are not supported
or converted to one of these types before formatting. Also it does not work with multiple
values.
b) Eg:
• >>>TestVar = ‘KLESNC’
• >>>’College : %s’ % TestVar
• ‘College : KLESNC’
works well when single value is passed. But if the variable TestVar were ever to be a tuple.,
the same code would fail.
• >>>TestVar = (‘KLESNC’, 560010)
• >>>’College : %s’ % TestVar
TypeError: not all arguments converted during string formatting.
b) Str.format:
This was added to address some of these problems with %-formatting.
Eg:
>>>value = 5 * 10
>>>’The value is {value}.’ .format(value = value)
‘The value is 50.’
>>> ‘The value is { }’ .format(value)
‘The value is 50.’
Example1
x="orange"
y="grapes“
print("This is {} and {}".format(x,y)) # Using positional placeholders
This is orange and grapes
print("This is {a} and {b}".format(a=x,b=y)) # Using named placeholders
This is orange and grapes
print(f"This is {x} and {y}") #using f-string
This is orange and grapes

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 strsplitdemo.py


Java is a programming language
['Java', 'is', 'a', 'programming', 'language']
Java, is, a, programming, language
['Java', 'is', 'a', 'programming', 'language']
String Methods in Python Cont..
☞ find():
• In python, find() method finds substring in the given string and returns
index of the first match. It returns -1 if substring does not match.
Syntax: str.find(sub[, start[,end]])
Example: strfinddemo.py
str1 = "python is a programming language"
str2 = str1.find("is")
str3 = str1.find("java")
str4 = str1.find("p",5)
str5 = str1.find("i",5,25)
print(str2,str3,str4,str5)

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 = "machine_learning" text = "data_analysis.py"


result = text.startswith("machine") result = text.startswith(("data", "info"))
print(result) print(result)
Output: True Output: True
String Methods in Python Cont..

Example 3: Specifying start and end

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..

Example 1: Basic count usage

my_string = "Hello, how are you?"


print(my_string.count("o"))
Outputs : 3 # “o” appears 3 times in the string

Example 2: Using start and end indices

my_string = "Hello, how are you?"


print(my_string.count("o", 5, 10))
Outputs: 1

You might also like