SlideShare a Scribd company logo
1 of 89
Download to read offline
1/89
October 28, 2022
Python Strings Methods
mrexamples.com/python/references/python-strings-methods
Strings Methods In Python
Here we learn Python strings methods in the hope that it will meet your educational
needs.
There are a number of Python built-in methods that can be used to manipulate
strings.
There is one thing to keep in mind when using string methods: they all return new values.
In other words, they do not change the original string in any way.
Python Strings Methods List
Methods Overview
capitalize() Uppercase the first character.
casefold() Makes string lowercase.
center() Python strings methods return centered strings.
count() A string’s frequency of a particular value.
encode() An encoded string is returned.
2/89
endswith() The string is true if it ends with the given value.
expandtabs() This property specifies the string’s tab size.
find() Returns the position where a specified value was found in the string in
Python.
format() String format for given values.
format_map() String format for given values.
index() Returns the point where a given value was found in the string.
isalnum() True if a string contains all alphanumeric characters.
isalpha() True if the string has all alphabetic characters.
isdecimal() True if all characters are decimals.
isdigit() Returns True if all characters in a string are digits.
isidentifier() Identifies the string with True.
islower() True if all characters are lowercase.
isnumeric() Numeric characters in the string are returned as True.
isprintable() True if the string has all printable characters.
isspace() Returns True if the string contains only whitespace.
istitle() True if the string follows title rules.
isupper() Python strings methods return True if all characters are uppercase.
join() Combines the elements of an iterable to the string’s end.
ljust() The string is left justified when returned.
lower() Lowers the case of a string.
lstrip() The string’s left trim version is returned.
maketrans() This method returns a translation table for use in translations.
partition() In Python strings methods, this function returns a tuple with the string
divided into three parts.
replace() Returns a string in which a specified value has been replaced with
another specified value.
rfind() The string is searched for a specific value, and the latest location
where it was found is returned.
rindex() The string is searched for a specific value, and the latest location
where it was found is returned.
3/89
rjust() Returns the string’s right justified version.
rpartition() Returns a tuple with the string divided into three parts.
rsplit() Returns a list after splitting the string at the provided separator.
rstrip() Returns the string’s right trim version.
split() Returns a list after splitting the string at the provided separator.
splitlines() Returns a list after splitting the string at line breaks.
startswith() If the string begins with the supplied value, this function returns true.
strip() This method returns a reduced version of the string.
swapcase() Cases are switched, with the lower case becoming upper case and
vice versa.
title() Every word’s initial character is converted to upper case.
translate() This function returns a translated string.
upper() This function converts a string to upper case.
zfill() Fills the string at the start with a defined set of 0 values.
It is imperative to note that Python strings methods return rewritten values. The
original string remains unchanged.
Python Strings Tutorial explains strings in more detail.
Python Strings Methods Examples
The following is an in-depth explanation of Python Strings Methods, with examples
for each method.
Python Strings Method capitalize()
Capitalize() method generates a string with the first character in upper case, and the
remaining characters in lower case.
Syntax:
string.capitalize()
There are no parameters. The following sentence begins with an uppercase letter:
Capitalize() Example:1
4/89
1
2
3
4
5
6
7
8
9
10
mrx_string = "hey!! future developers, welcome to the python strings method."
ample = mrx_string.capitalize()
print (ample)
We convert the first character to uppercase, and the following characters to lowercase:
Capitalize() Example:2
1
2
3
4
5
6
7
8
9
10
mrx_string = "python is an easiest, modern Programming Language"
ample = mrx_string.capitalize()
print (ample)
Try it with a number as the first character:
Capitalize() Example:3
1
2
3
5/89
4
5
6
7
8
9
10
mrx_string = "1991 was the year when the first version of Python was released."
ample = mrx_string.capitalize()
print (ample)
As a first character, test a symbol:
Capitalize() Example:4
1
2
3
4
5
6
7
8
9
10
mrx_string = "# is used as a comment symbol in Python."
ample = mrx_string.capitalize()
print (ample)
Python Strings Method casefold()
Python String Casefold() generates a string with all characters in lower case.
In comparison to lower(), casefold() is better, more efficient, indicating that it will
transform more characters into lower case, and will find more matches when comparing
two strings transformed by casefold().
Syntax:
string.casefold()
There are no parameters. Change the string to lower case:
6/89
Casefold() Example:1
1
2
3
4
5
6
7
8
9
10
mrx_string = "Hey!! Future developers, Welcome to the Python strings method."
ample = mrx_string.casefold()
print(ample)
Try it with a number as the first character:
Casefold() Example:2
1
2
3
4
5
6
7
8
9
10
mrx_string = "1991 was the year when the First Version of Python was released."
ample = mrx_string.casefold()
print(ample)
Python Strings Method center()
Python String Center() method will position the string in the center, using a given
character as fill (space by default).
Syntax:
7/89
string.center(length, character)
Parameter Values
Parameter Summary
length It is necessary. Provide the length of the string
character A choice. Fill in the missing space on each side with this character. The
default value is ” ” (empty space).
In the center of the 70 characters, display the word “mrexamples”:
Center() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "mrexamples"
ample = mrx.center(70)
print(ample)
Utilizing the symbol “*” as the padding character:
Center() Example:2
1
2
3
4
5
6
7
8
8/89
9
10
mrx = "mrexamples"
ample = mrx.center(70, "*")
print(ample)
First implement the casefold() method to string then apply the center() method:
Center() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
mrx = "MReXamples"
mrx = mrx.casefold()
ample = mrx.center(70, "!")
print(ample)
Python Strings Method count()
The Count() method displays the occurrences of a given value present in the string.
Syntax:
string.count(value, start, end)
Parameter Values
Parameter Summary
value This is necessary.
A String.
Look for the string value.
9/89
start A choice. It is an integer.
Begin the search at this position – It is set to 0 by default.
end A choice. This is an integer.
You can stop the search at this position.
Strings are terminated at the end by default.
Find out how many times the string contains the word “python“:
Count() Example:1
1
2
3
4
5
6
7
8
9
10
11
mrx = "Python is a high-level programming language and in python language we can use
multiple python strings methods which can help us during python programming."
mrx = mrx.casefold()
ample = mrx.count("python")
print(ample)
From position 15 to 154, find as follows:
Count() Example:2
1
2
3
4
5
6
7
8
9
10/89
10
mrx = "Python is a high-level programming language and in python language we can use
multiple python strings methods which can help us during python programming."
ample = mrx.count("python",15,154)
print(ample)
First apply the capitalize() method to the string then utilize the count() method:
Count() Example:3
1
2
3
4
5
6
7
8
9
10
11
mrx = "python is a high-level programming language and in python language we can use
multiple python strings methods which can help us during python programming."
mrx = mrx.capitalize()
ample = mrx.count("python",0,60)
print(ample)
Python Strings Method encode()
The Encode() method encodes a string with the given encoding. In the absence of an
encoding standard, UTF-8 will be utilized.
Syntax:
string.encode(encoding=encoding, errors=errors)
Parameter Values
Parameter Summary
encoding A choice. Indicates the encoding to be used. The default character
encoding is UTF-8
11/89
errors The optional part. Indicates the error method in a string. The following
values are legal:
‘backslashreplace’ Replace the unencoded character with a backslash
‘ignore’ Pass over unencoded characters
‘namereplace’ Put a description of the character in place of the character
‘strict’ Failure throws an exception by default
‘replace’ A question mark appears instead of the character
‘xmlcharrefreplace’ An XML character is substituted for the character
Using UTF-8, encode the string as follows:
Encode() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "Python pronunciation: ˈpīˌTHän"
ample = mrx.encode()
print(ample)
The following examples use ASCII encoding and a character that is unable to be encoded,
displaying various errors:
Encode() Example:2
1
2
3
4
12/89
5
6
7
8
9
10
11
12
mrx = "Python pronunciation: ˈpīˌTHän"
print(mrx.encode(encoding="ascii",errors="backslashreplace"))
print(mrx.encode(encoding="ascii",errors="ignore"))
print(mrx.encode(encoding="ascii",errors="namereplace"))
print(mrx.encode(encoding="ascii",errors="replace"))
print(mrx.encode(encoding="ascii",errors="xmlcharrefreplace"))
Implement the center() method to the string then utilize the encode() method to
display the various errors of the characters that are not able to encode.
Encode() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
mrx = "ⓜⓡⓧⓔⓧⓐⓜⓟⓛⓔ"
print(mrx.center(70, "*"))
print(mrx.encode(encoding="ascii",errors="backslashreplace"))
print(mrx.encode(encoding="ascii",errors="ignore"))
print(mrx.encode(encoding="ascii",errors="namereplace"))
print(mrx.encode(encoding="ascii",errors="replace"))
print(mrx.encode(encoding="ascii",errors="xmlcharrefreplace"))
13/89
Python Strings Method endswith()
When the string ends with the given value, the endswith() method provides True, else
False.
Syntax:
string.endswith(value, start, end)
Parameter Values
Parameter Summary
value This is necessary. Verify if the string ends with.
start This is optional. The location at which to begin the search as an integer.
end A choice. Indicates where to end the look for as an integer.
If there is a punctuation mark (?) at the end of the string, verify it:
Endswith() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "Do you know about python strings method?"
ample = mrx.endswith("?")
print(ample)
If the string ends with “method?” verify the following:
Endswith() Example:2
1
14/89
2
3
4
5
6
7
8
9
10
mrx = "Do you know about python strings method?"
ample = mrx.endswith("method?")
print(ample)
If position 0 to 14 ends with “Python strings methods?“, verify the following:
Endswith() Example:3
1
2
3
4
5
6
7
8
9
10
mrx = "Do you know about python strings method?"
ample = mrx.endswith("python strings method?", 0, 14)
print(ample)
Encode the string message utilizing the encode() method then apply the endswith()
method to verify the string ends with “python strings methods?”:
Endswith() Example:4
1
2
3
4
5
15/89
6
7
8
9
10
11
12
mrx = "Do you know about python strings methods?"
print(mrx.encode())
ample = mrx.endswith("python strings methods?", 0, len(mrx))
print(ample)
Python Strings Method expandtabs()
By calling the expandtabs() method, the tab size is set to the number of whitespaces
given.
Syntax:
string.expandtabs(tabsize)
Parameter Values
Parameter Summary
tabsize A choice. A number indicating the tabsize – Tabsize is set to 8 by default
To set the tab size to three blank spaces:
Expandtabs() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "MtRt.tEtXtAtMtPtLtE"
16/89
ample = mrx.expandtabs(4)
print(ample)
Apple the casefold() method and count() method then set the tab size to four blank
spaces:
Expandtabs() Example:2
1
2
3
4
5
6
7
8
9
10
11
12
mrx = "MtRt.tEtXtAtMtPtLtE"
mrx = mrx.casefold()
print(mrx.count("t"))
ample = mrx.expandtabs(4)
print(ample)
Utilizing various tab sizes, you can examine the results:
Expandtabs() Example:3
1
2
3
4
5
6
7
8
9
10
11
17/89
12
13
mrx = "MtRt.tEtXtAtMtPtLtE"
print(mrx)
print(mrx.expandtabs())
print(mrx.expandtabs(2))
print(mrx.expandtabs(4))
print(mrx.expandtabs(6))
print(mrx.expandtabs(10))
Python Strings Method find()
The find() method locates the initial appearance of the given value.
If the value cannot be located, find() method displays -1.
There is only one difference between the find() method and the index() method. If the
value cannot be found, the index() method throws an error. (Refer to the below example)
Syntax
string.find(value, start, end)
Parameter Values
Parameter Summary
value This is necessary. A String. Look for the string value.
start A choice. Begin the search at this position. It is set to 0 by default.
end A choice. You can stop the search at this position. Strings are terminated
at the end by default.
What is the location of the word “python” in the text? :
Find() Example:1
1
2
3
4
5
6
18/89
7
8
9
10
mrx = "Hey future developer!, welcome to the python string find() method."
ample = mrx.find("python")
print(ample)
What is the first appearance of “r” in the text? :
Find() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = "Hey future developer!, welcome to the python string find() method."
ample = mrx.find("r")
print(ample)
If you only search between positions 20 and len(mrx), where is the first appearance of
the character “r“? :
Find() Example:3
1
2
3
4
5
6
7
8
9
10
19/89
mrx = "Hey future developer!, welcome to the python string find() method."
ample = mrx.find("r", 20, len(mrx))
print(ample)
The find() method returns -1 if the value could not be located, but the index() method
will throw an error:
Find() Example:4
1
2
3
4
5
6
7
8
9
mrx = "Hey future developer!, welcome to the python string find() method."
print(mrx.find("z")) #returns -1
print(mrx.index("z")) #throws an exception
Capitalize the string first, utilize the count() method to the capitalized string then apply
the find() method:
Find() Example:5
1
2
3
4
5
6
7
8
9
10
11
12
mrx = "hey future developer!, welcome to the python string find() method."
mrx = mrx.capitalize()
20/89
print(mrx)
print(mrx.count("H"))
ample = mrx.find("h")
print(ample)
Python Strings Method format()
The Format() method formats the given value(s) and adds them to the string’s
placeholder.
Curly brackets are utilized to identify the placeholder: {}. In the Placeholder area below,
you can learn a lot about placeholders.
The format() method provides a well-formatted string.
Syntax
string.format(value1, value2...)
Parameter Values
Parameter Summary
value1,
value2…
It is necessary. In the string, one or several values must be
formatted
and added.
It can also be a list of items divided by commas, a key-value list, or
a mixture of both.
Any data type can be utilized for the values.
Place the net_worth in the placeholder, in three-digit fixed point form:
Format() Example:1
1
2
3
4
5
6
7
21/89
8
mrx = "The net worth of Bernard Arnault is $164.000 billion"
print(mrx.format(net_worth = 164))
Placeholders
It is feasible to recognize the placeholders based on their names {net_worth}, numbers
{0}, or possibly by empty placeholders {}.
Placing a variety of placeholder values:
Placeholder Example:1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#Indexed with names:
mrx1 = "Name: {name}, Age: {age}, Residence: {res}, Net worth:
{n_worth}".format(name = "Elon Musk", age = 51, res = "Texas", n_worth = "$128
billion")
#Indexed with numbers:
mrx2 = "Name: {0}, Age: {1}, Residence: {2}, Net worth: {3}".format("Bill Gates", 67,
"Washington", "$109 billion")
#Placeholders that are void:
mrx3 = "Name: {}, Age: {}, Residence: {}, Net worth: {}".format("Jeff Bezos", 58,
"Washington", "$109 billion")
print(mrx1)
print(mrx2)
print(mrx3)
22/89
Utilize the center() method to display the “Billionaires” string in the center and place a
variety of placeholder values. In the last step, apply the capitalize(), casefold() and
find() methods to the strings:
Placeholder Example:2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#Indexed with names:
print("Billionaires".center(70))
mrx1 = "Name: {name}, Age: {age}, Residence: {res}, Net worth:
{n_worth}".format(name = "Elon Musk", age = 51, res = "Texas", n_worth = "$128
billion")
#Indexed with numbers:
mrx2 = "Name: {0}, Age: {1}, Residence: {2}, Net worth: {3}".format("Bill Gates", 67,
"Washington", "$109 billion")
#Placeholders that are void:
mrx3 = "Name: {}, Age: {}, Residence: {}, Net worth: {}".format("Jeff Bezos", 58,
"Washington", "$109 billion")
print(mrx1.capitalize())
print(mrx2.casefold())
print(mrx3.find("Washington"))
Formatting Types
Insert a formatting type within the placeholders to format the output:
:< Position the results to the left (using free space).
23/89
:> Position the results to the right (using free space).
:^ Position the results to the center (using free space).
:= Orient the sign to the left
:+ To represent a positive or negative outcome, utilize a plus sign
:- You must write a minus sign for negative values
: To precede positive numbers, add a space (and to precede negative numbers, a
minus sign).
:, As a thousand separator, utilize a comma
:_ In place of a thousand separator, utilize an underscore
:b Binary format
:c Obtain the corresponding Unicode character from the value
:d Decimal format
:e Utilizing a smaller case e in scientific format
:E Utilizing a larger case E in scientific format
:f Correct point number format
:F Format point numbers in uppercase (show infs and nans as INFs and NANS)
:g General format
:G For scientific notation, utilize an uppercase E.
Octal format
Hex format, smaller case
:X Hex format, larger case
:n Number format
:% Percentage format
Python Strings Method index()
By calling the index() method, you can locate the first appearance of a value you provide.
If the value cannot be located, index() throws an error.
The index() method is almost identical to the find() method, with the exception that the
find() method provides -1 if no value is located. (Check out the example below)
24/89
Syntax
string.index(value, start, end)
Parameter Values
Parameter Summary
value This is necessary.
A String.
Look for the string value.
start A choice.
Begin the search at this position.
It is set to 0 by default.
end A choice. You can stop the search at this position – Strings are terminated
at the end by default.
What is the location of the word “python” in the text? :
Index() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "Hey future developer!, welcome to the python string index() method."
ample = mrx.index("python")
print(ample)
What is the first appearance of “r” in the text? :
Index() Example:2
25/89
1
2
3
4
5
6
7
8
9
10
mrx = "Hey future developer!, welcome to the python string index() method."
ample = mrx.index("r")
print(ample)
If you only search between positions 20 and len(mrx), where is the first appearance of
the character “r”? :
Index() Example:3
1
2
3
4
5
6
7
8
9
10
mrx = "Hey future developer!, welcome to the python string index() method."
ample = mrx.index("r", 20, len(mrx))
print(ample)
The find() method returns -1 if the value could not be located, but the index() method
will throw an error:
Index() Example:4
1
2
26/89
3
4
5
6
7
8
9
mrx = "Hey future developer!, welcome to the python string index() method."
print(mrx.index("z")) #throws an exception
print(mrx.find("z")) #returns -1
Capitalize the string first, utilize the count() method to the capitalized string then apply
the index() method:
Index() Example:5
1
2
3
4
5
6
7
8
9
10
11
12
mrx = "hey future developer!, welcome to the python string index() method."
mrx = mrx.capitalize()
print(mrx)
print(mrx.count("H"))
ample = mrx.index("h")
print(ample)
Python Strings Method isalnum()
When all the characters are letters (a-z) and digits (0-9), then the isalnum() method
produces True.
Non-alphanumeric characters: (space)!#%&? etc.
27/89
Syntax
string.isalnum()
Parameters are not required – Make sure each of the characters in the string is
alphanumeric:
Isalnum() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "Nimbus2000"
ample = mrx.isalnum()
print(ample)
Verify that each of the characters in the string is alphanumeric:
Isalnum() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = "iPhone 14"
ample = mrx.isalnum()
print(ample)
28/89
Apply the underscore to the alphanumeric string:
Isalnum() Example:3
1
2
3
4
5
6
7
8
9
10
mrx = "iPhone_14"
ample = mrx.isalnum()
print(ample)
Python Strings Method isascii()
If each of the characters are ASCII characters, the isascii() method displays True.
Syntax
string.isascii()
Parameters are not required – Make sure each of the characters in the string is ASCII:
Isascii() Example:1
1
2
3
4
5
6
7
8
9
29/89
10
mrx = "Rain, snow, mud, and off-road conditions are no problem for the Model Y of
Tesla."
ample = mrx.isascii()
print(ample)
Verify that each character in the mrx string is ASCII:
Isascii() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = "Python pronunciation: ˈpīˌTHän"
ample = mrx.isascii()
print(ample)
Python Strings Method isdecimal()
If each of the characters is a decimal (0-9), the isdecimal() method outputs True.
Unicode objects utilize this method.
Syntax
string.isdecimal()
Parameters are not required – Verify that all the characters in the Unicode object are
decimal:
Isdecimal() Example:1
1
30/89
2
3
4
5
6
7
8
9
10
mrx = "u0039" #unicode for 9
ample = mrx.isdecimal()
print(ample)
Make sure that each of the characters in Unicode are decimals:
Isdecimal() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = "u0036" #unicode for 6
ample = "u0041" #unicode for A
print(mrx.isdecimal())
print(ample.isdecimal())
Ensure that each Unicode character is a decimal:
Isdecimal() Example:3
1
2
3
4
5
31/89
6
7
8
9
10
11
12
mrx1 = "u0038" #unicode for 8
mrx2 = "u0048" #unicode for H
mrx3 = "u005F" #unicode for underscore(_)
print(mrx1.isdecimal())
print(mrx2.isdecimal())
print(mrx3.isdecimal())
Python Strings Method isdigit()
If each and every character is digits, the isdigit() method provides True, else False.
Numbers with exponents, such as ², are also regarded as digits.
Syntax
string.isdigit()
Parameters are not required – Verify that all of the string characters are numbers:
Isdigit() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "7800000"
ample = mrx.isdigit()
print(ample)
32/89
First, separate the thousand by an underscore, then verify that all string characters are
digits:
Isdigit() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = "10_000_000"
ample = mrx.isdigit()
print(ample)
Prove that all of the string characters are numbers:
Isdigit() Example:3
1
2
3
4
5
6
7
8
9
10
mrx = "u0039" #unicode for 9
ample = "u00B3" #unicode for ³
print(mrx.isdigit())
print(ample.isdigit())
Python Strings Method isidentifier()
33/89
If the string is a correct identifier, isidentifier() provides True, else False.
Strings with only alphanumeric characters (a-z) and zero through nine, or underscores
(_), are accepted as correct identifiers.
A correct identifier cannot begin with a number or include any spaces.
Syntax
string.isidentifier()
Parameters are not required – Verify that the string is a correct identifier:
Isidentifier() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "mrexamples"
ample = mrx.isidentifier()
print(ample)
Make sure the string is the correct identifier:
Isidentifier() Example:2
1
2
3
4
5
6
7
8
34/89
9
10
mrx = "isidentifier_Method"
ample = mrx.isidentifier()
print(ample)
To find out if the strings are correct identifiers, check the following:
Isidentifier() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mrx1 = "mrx-1"
mrx2 = "Mrx1"
mrx3 = "1ample"
mrx4 = "ample one"
mrx5 = "Mrx_1"
mrx6 = "@mple"
print(mrx1.isidentifier())
print(mrx2.isidentifier())
print(mrx3.isidentifier())
print(mrx4.isidentifier())
print(mrx5.isidentifier())
print(mrx6.isidentifier())
35/89
Python Strings Method islower()
If all the letters are in small case, the islower() method outputs True, else outputs
False.
Only alphabetic characters are validated, not numbers, symbols, or spaces.
Syntax
string.islower()
There are no parameters – Make sure all the letters in the string are lowercase:
Islower() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "hey!! future developers, welcome to the python string islower() method."
ample = mrx.islower()
print(ample)
If the first character in a string is a digit, ensure that all the characters are in lower case:
Islower() Example:2
1
2
3
4
5
6
7
8
36/89
9
mrx = "1991 was the year when the first version of python was released."
ample = mrx.islower()
print(ample)
Verify that all the letters in the multiple strings are in smaller case:
Islower() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
mrx1 = "mr_examples"
mrx2 = "iphone 14"
mrx3 = "Steve Jobs is the owner of the Apple company"
mrx4 = "iphoneX"
print(mrx1.islower())
print(mrx2.islower())
print(mrx3.islower())
print(mrx4.islower())
Python Strings Method isnumeric()
When all characters (0-9 are numeric), isnumeric() provides True, else it gives False.
Numerical values include exponents, such as ⁷ and ¾.
“-7” and “4.5” are unable to be accepted as numeric values, because every characters in
the string have to be numeric, and the – and “.” are not.
Syntax
37/89
string.isnumeric()
Parameters are not required – Verify that all of the string characters are numeric:
Isnumeric() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "2³"
ample = mrx.isnumeric()
print(ample)
First, separate the thousand by a comma in the string, then verify that all string characters
are numeric:
Isnumeric() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = "48,000,000"
ample = mrx.isnumeric()
print(ample)
Make sure the characters are in numeric form:
38/89
Isnumeric() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mrx1 = "u0039" #unicode for 9
mrx2 = "u00B3" #unicode for ³
mrx3 = "90mph"
mrx4 = "3.67"
mrx5 = "-7"
mrx6 = "7¾"
print(mrx1.isnumeric())
print(mrx2.isnumeric())
print(mrx3.isnumeric())
print(mrx4.isnumeric())
print(mrx5.isnumeric())
print(mrx6.isnumeric())
Python Strings Method isprintable()
Isprintable() returns True if all characters are printable, otherwise False.
In addition to carriage returns and line breaks, there are several non-printable characters.
Syntax
string.isprintable()
39/89
Parameters are not required – Verify that all of the string characters are printable:
Isprintable() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "Tesla latest model: Model Y"
ample = mrx.isprintable()
print(ample)
Make sure the string is printable by checking the following:
Isprintable() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = "Tesla latest model:tModel Y"
ample = mrx.isprintable()
print(ample)
Ensure that all the characters in the string are printable:
Isprintable() Example:3
40/89
1
2
3
4
5
6
7
8
9
10
mrx = "#Tesla latest model:nModel Y"
ample = mrx.isprintable()
print(ample)
Python Strings Method isspace()
If all the characters in a string are empty spaces, the isspace() method returns True,
while it returns False.
Syntax
string.isspace()
Parameters are not required – Make sure all the characters in the string are empty spaces:
Isspace() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = " "
ample = mrx.isspace()
print(ample)
41/89
Verify that all the characters in the string are blank spaces:
Isspace() Example:2
1
2
3
4
5
6
7
8
9
10
mrx = " MRX "
ample = mrx.isspace()
print(ample)
Find out that all the characters in the string are empty spaces:
Isspace() Example:3
1
2
3
4
5
6
7
8
9
10
mrx = "Mr examples"
ample = mrx.isspace()
print(ample)
Python Strings Method istitle()
42/89
When all words in a text have an uppercase letter and the remainder are lowercase letters,
the istitle() method provides True; else, it provides False.
It is not necessary to include symbols or numbers.
Syntax
string.istitle()
Parameters are not required – Make sure every word begins with an uppercase letter:
Istitle() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "Guido Van Rossum Is The Founder Of Python Language"
ample = mrx.istitle()
print(ample)
Verify that every word begins with an uppercase letter in the following example:
Istitle() Example:2
1
2
3
4
5
6
7
8
9
10
43/89
mrx = "Guido Van Rossum Is The Founder Of PYTHON Language"
ample = mrx.istitle()
print(ample)
In the following example, ensure that each word in the string begins with an uppercase
letter:
Example:
1
Python Strings Method isupper()
If all the letters are in larger case, the isupper() method outputs True, else outputs
False.
Only alphabetic characters are validated, not numbers, symbols, or spaces.
Syntax
string.isupper()
There are no parameters – Make sure all the letters in the string are uppercase:
Isupper() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "HELLO PYTHON DEVELOPERS!!"
ample = mrx.isupper()
print(ample)
If the first character in a string is a digit, ensure that all the characters are in upper case:
44/89
Isupper() Example:2
1
2
3
4
5
6
7
8
9
mrx = "1991 WAS THE YEAR WHEN THE FIRST VERSION OF PYTHON WAS
RELEASED."
ample = mrx.isupper()
print(ample)
Verify that all the letters in the multiple strings are in larger case:
Isupper() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
mrx1 = "MR_EXAMPLES"
mrx2 = "IPHONE 14"
mrx3 = "Steve Jobs is the owner of the Apple company"
mrx4 = "iPHONE 14 PRO MAX"
print(mrx1.isupper())
print(mrx2.isupper())
45/89
print(mrx3.isupper())
print(mrx4.isupper())
Python Strings Method join()
In the join() method, each of the elements in an iterable is joined into a single string.
As a separator, you have to provide a string.
Syntax
string.join(iterable)
Parameter Values
Parameter Summary
iterable It is necessary. If all the retrieved items are strings, then the iterable
object is String.
By applying a ” –> ” as a separator, join all elements in a tuple into a string:
Join() Example:1
1
2
3
4
5
6
7
8
9
10
digit_tuple = ("1", "2", "3", "4", "5")
mrx = " --> ".join(digit_tuple)
print(mrx)
Utilize a “n” as a separator, join all elements in a tuple into a string:
Join() Example:2
46/89
1
2
3
4
5
6
7
8
9
10
digit_tuple = ("1", "2", "3", "4", "5")
mrx = "n".join(digit_tuple)
print(mrx)
Create a string by connecting all entries in a dictionary with the word “TRY” as a
separating word:
Join() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
bio_dict = {"name": "Harry", "age":19, "profession": "Football", "country": "United Sates
of America"}
separate_by = "TRY"
mrx = separate_by.join(bio_dict)
print(mrx)
Reminder: As an iterable, a dictionary displays the keys, not the values.
Python Strings Method ljust()
47/89
By calling the ljust() method, a chosen character (space by default) will be assigned as
the fill character of the string.
Syntax
string.ljust(length, character)
Parameter Values
Parameter Summary
length This is necessary.
Provides the length of the string.
character A choice. To occupy the blank space (to the right of the string),
enter a character. The default value is ” ” (space).
By applying a ” –> ” as a separator, join all elements in a tuple into a string:
ljust() Example:1
1
2
3
4
5
6
7
8
9
10
mrx = "Python"
ample = mrx.ljust(35)
print(ample, "is the easiest programming language.")
Utilize a “n” as a separator, join all elements in a tuple into a string:
ljust() Example:2
1
48/89
2
3
4
5
6
7
8
9
10
mrx = "PYTHON"
ample = mrx.ljust(50, "*")
print(ample)
Create a string by connecting all entries in a dictionary with the word “TRY” as a
separating word:
ljust() Example:3
1
2
3
4
5
6
7
8
9
10
11
12
13
bio_dict = {"name": "Harry", "age":19, "profession": "Football", "country": "United Sates
of America"}
separate_by = "TRY"
mrx = separate_by.join(bio_dict)
print(mrx)
Python Strings Method lower()
lower() method generates a string that contains all letters in small case.
Numbers and symbols are not taken into account.
49/89
Syntax
string.lower()
There are no parameters – Make the string smaller case:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Welcome to PYTHON Strings lower() Method."
ample = mrx.lower()
print(ample)
Apply the digits at the beginning of the string then convert the string to small case:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "3.11.1 is the latest version of PYTHON!"
ample = mrx.lower()
print(ample)
50/89
Python Strings Method lstrip()
lstrip() eliminates any preceding characters (the space character is the default preceding
character).
Syntax
string.ljust(length, character)
Parameter Values
Parameter Description
characters A choice. To eliminate as main characters a set of characters.
Left-justify the string by eliminating spaces:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = " BEST>>>>>>>>>"
ample = mrx.lstrip()
print("Python is the", ample,"Programming Language")
Pass the value “>” in the lstrip() method:
Example:
1
2
3
4
51/89
5
6
7
8
9
10
mrx = " BEST>>>>>>>>>"
ample = mrx.lstrip(">")
print("Python is the", ample,"Programming Language")
Take out the preceding characters:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "-->-->-->-->-->-->BEST>>>>>>>>>"
ample = mrx.lstrip("->")
print("Python is the", ample,"Programming Language")
Python Strings Method maketrans()
Maketrans() method provides a mapping table that can be utilized with the translate()
method to substitute selected characters.
Syntax
string.maketrans(x, y, z)
Parameter Values
Parameter Description
52/89
x This is necessary. A dictionary explaining how to execute the substitution
must be given if only one parameter is given. A string indicating the
characters to substitute must be given if two or more parameters are
given.
y A choice. The length of the string is the same as the parameter x. In this
string, every character in the initial parameter will be substituted with its
equivalent character.
z A choice. Indicates which characters must be deleted from the original
string.
Utilize the mapping table in the translate() method to substitute any “G” characters for
“H” characters:
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "Garry: We are learning python string maketrans() methods"
ample = mrx.maketrans("G", "H")
print(ample) #showing decimal number of ASCII characters G and H
print(mrx.translate(ample))
Initially implement the lower() method on string, then apply the maketrans() method:
Example:
1
2
3
4
5
53/89
6
7
8
9
10
11
12
mrx = "KANE: We are learning Python String Methods"
mrx = mrx.lower()
ample = mrx.maketrans("k", "j")
print(mrx.translate(ample))
To substitute multiple characters, utilize a mapping table:
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
mrx = "Eva"
ample1 = "aEv"
ample2 = "yAm"
mrx_table = mrx.maketrans(ample1, ample2)
print(mrx.translate(mrx_table))
You can delete characters from the string through the third parameter in the mapping
table:
Example:
1
54/89
2
3
4
5
6
7
8
9
10
11
12
13
14
mrx = "Bonjour Eva!!"
ample1 = "Eva"
ample2 = "Lia"
ample3 = "Bonjour"
mrx_table = mrx.maketrans(ample1, ample2, ample3)
print(mrx.translate(mrx_table))
In Unicode, the maketrans() method generates a dictionary explaining each
substitution:
Example:
1
2
3
4
5
6
7
8
9
10
11
12
mrx = "Bonjour Eva!!"
ample1 = "Eva"
ample2 = "Lia"
ample3 = "Bonjour"
print(mrx.maketrans(ample1, ample2, ample3))
55/89
Python Strings Method partition()
Through the partition() method, you can look for a string and divide it into tuples with
three elements.
In the first element, the part preceding the given string is included.
The string mentioned in the second element can be found in the second element.
After the string, the third element includes the part.
Reminder: This method finds the initial appearance of the given string.
Syntax
string.partition(value)
Parameter Values
Parameter Description
value It is necessary. Specify the search string
Provide a tuple with three elements that include the word “partition()“:
1. Anything that precedes “equivalent”
2. The “equivalent”
3. Anything that follows “equivalent”
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Python Strings partition() Method"
ample = mrx.partition(" partition() ")
print(ample)
56/89
Apply the title() method to the mrx string, then utilize the partition() method:
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "python strings method"
mrx = mrx.title()
ample = mrx.partition("Strings")
print(ample)
Partition() method generates a tuple with: first the whole string, second an unfilled
string, third an unfilled string if the given value is not present:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Python Strings partition() Method"
ample = mrx.partition("maketrans()")
print(ample)
57/89
Python Strings Method replace()
By calling the replace() method, you can substitute a phrase for a new phrase.
Reminder: A substitution will be executed on all occurrences of the given phrase if
nothing else is provided.
Syntax
string.replace(oldvalue, newvalue, count)
Parameter Values
Parameter Description
oldvalue It is necessary. Specify the search string
newvalue This is necessary. Replacement string for the previous value
count A choice. The number of instances of the previous value you want to
replace. All instances are set to default.
Substitute “3.8.0” to “3.11.1”:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Latest version of Python is 3.8.0"
ample = mrx.replace("3.8.0", "3.11.1")
print(ample)
Utilize the replace() method on a string, then implement the partition() method:
Example:
58/89
1
2
3
4
5
6
7
8
9
10
11
txt = "Black…White…Blue"
x = txt.replace("…", "")
ample = x.partition("White")
print(ample)
Change all appearances of “two” to “nine”:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "The net worth of Bill Gates is one hundred two billion dollars, and Jeff Bezos is
also one hundred two billion dollars."
ample = mrx.replace("two", "nine")
print(ample)
Change the first appearance of the word “two” to “nine”:
Example:
1
59/89
2
3
4
5
6
7
8
9
10
mrx = "The net worth of Bill Gates is one hundred two billion dollars, and Jeff Bezos is
also one hundred two billion dollars."
ample = mrx.replace("two", "nine", 1)
print(ample)
Python Strings Method rfind()
rfind() method locates the last appearance of a value.
A value cannot be located if the rfind() method returns -1.
The rfind() method is nearly identical to the rindex() method. You can see an example
below.
Syntax
string.rfind(value, start, end)
Parameter Values
Parameter Description
value It is necessary. Specify the search string.
start A choice. Searching for where to begin. It is set to 0 by default.
end A choice. End the search here. As default, it ends at the last.
In what part of the text does the string “language” occur at the end? :
Example:
1
2
60/89
3
4
5
6
7
8
9
10
mrx = "Python is an easy to learn language but it is also a vast language"
ample = mrx.rfind("language")
print(ample)
Utilize the count() method on a string, then apply the rfind() method:
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "Python is an easy to learn language but it is also a vast language"
print(mrx.count("language"))
ample = mrx.rfind("language")
print(ample)
In the string where is the last appearance of the character “o”? :
Example:
1
2
3
4
5
61/89
6
7
8
9
10
mrx = "Greetings, we are learning about the Python rfind() method"
ample = mrx.rfind("o")
print(ample)
When you only find between positions 0 and 36, where is the final appearance of the
character “t”? :
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Greetings, we are learning about the Python rfind() method"
ample = mrx.rfind("t", 0, 36)
print(ample)
The rfind() method provides -1 if the value cannot be located, but the rindex() method
throws an error if the value cannot be found:
Example:
1
2
3
4
5
6
7
8
62/89
9
mrx = "Greetings, we are learning about the Python rfind() method"
print(mrx.rfind("x"))
print(mrx.rindex("x"))
Python Strings Method rindex()
The rindex() method searches for the last instance of a given value.
If the value is not found, an error will occur.
It is essentially identical to the rfind() method- please refer to the example for more
information.
Syntax
string.rindex(value, start, end)
Parameter Values
Parameter Description
value It is necessary. Specify the search string.
start A choice. Searching for where to begin. It is set to 0 by default.
end A choice. End the search here. As default, it ends at the last.
In what part of the text does the string “language” occur at the end? :
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Python is an easy to learn language but it is also a vast language"
63/89
ample = mrx.rindex("language")
print(ample)
Utilize the count() method on a string, then apply the rindex() method:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Python is an easy to learn language but it is also a vast language"
print(mrx.count("language"))
ample = mrx.rindex("language")
print(ample)
In the string where is the last appearance of the character “o”? :
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Greetings, we are learning about the Python rfind() method"
ample = mrx.rfind("o")
print(ample)
When you only find between positions 0 and 36, where is the final appearance of the
character “t”? :
64/89
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Greetings, we are learning about the Python rindex() method"
ample = mrx.rindex("t", 0, 36)
print(ample)
The rfind() method provides -1 if the value cannot be located, but the rindex() method
throws an error if the value cannot be found:
Example:
1
2
3
4
5
6
7
8
9
mrx = "Greetings, we are learning about the Python rindex() method"
print(mrx.rindex("x"))
print(mrx.rfind("x"))
Python Strings Method rjust()
The rjust() method aligns text to the right side of a string, utilizing either a space or a
given character as padding.
65/89
Syntax
string.rjust(length, character)
Parameter Values
Parameter Description
length This is necessary. Provides the length of the string
character A choice. To occupy the blank space (to the left of the string), enter a
character. The default value is ” ” (space).
Provide a right-aligned 35-character representation of “Python”:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Python"
ample = mrx.rjust(35)
print(ample, "is the easiest programming language.")
As a padding character, utilize the symbol “*”:
Example:
1
2
3
4
5
6
66/89
7
8
9
10
mrx = "PYTHON"
ample = mrx.rjust(50, "*")
print(ample)
For a padding character, apply the symbols “>” and “<“:
Example:
1
2
3
4
5
6
mrx1 = "String "
mrx2 = "rjust() "
ample1 = mrx1.rjust(30, ">")
ample2 = mrx2.rjust(30, "
Python Strings Method rpartition()
The rpartition() method looks for the final instance of a given string, which it then
divides into a tuple of three elements: The part before the string, the string itself, and the
part after it.
Syntax
string.rpartition(value)
Parameter Values
Parameter Description
value It is necessary. Specify the search string.
Provide a tuple with three elements that include the word “rpartition()“:
1 – Anything that precedes “equivalent”
2 – the “equivalent”
3 – Anything that follows “equivalent”
67/89
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Programming language Python has the rpartition() method. In Python it's a built-
in method"
ample = mrx.rpartition("Python")
print(ample)
Apply the title() method to the mrx string, then utilize the rpartition() method:
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "programming language python has the rpartition() method. In python it's a built-
in method"
mrx = mrx.title()
ample = mrx.rpartition("Python")
print(ample)
The rpartition() method generates a tuple with: first an unfilled string, second an
unfilled string if the given value is not present, third the whole string:
68/89
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "programming language python has the rpartition() method. In python it's a built-
in method"
ample = mrx.rpartition("rfind()")
print(ample)
Python Strings Method rsplit()
The rsplit() method will separate a string into a list beginning from the right, unless the
“max” parameter is set. It results in the same outcome as the split() function.
Reminder: When maxsplit is given, the resulting list can include up to that many
elements plus one.
Syntax
string.rsplit(separator, maxsplit)
Parameter Values
Parameter Description
separator A separator can be chosen (optional), and by default, any whitespace will
be used for splitting the string.
maxsplit The number of splits is optional. The default value is -1, meaning all
instances will be split.
Divide a string into a list by utilizing a comma and a space (“, “) as the delimiter.
Example:
69/89
1
2
3
4
5
6
7
8
9
10
mrx = "Python, Java, C, C++, C#, PHP"
ample = mrx.rsplit(", ")
print(ample)
Apply the rsplit() method to the mrx string, then utilize the join() method:
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "Python, Java, C, C++, C#, PHP"
ample = mrx.rsplit(", ")
ample1 = "–".join(ample)
print(ample1)
Divide the string into a list of at most 4 items:
Example:
1
70/89
2
3
4
5
6
7
8
9
10
11
12
13
14
mrx = "Python, Java, C, C++, C#, PHP"
# By setting the maxsplit parameter to 3, you will get a list of 4 elements!
ample = mrx.rsplit(", ", 3)
print(ample)
# The output has four values. 'Python, Java, C' is the first, 'C++' is the second, 'C#' is the
third, 'PHP' is the last.
Python Strings Method rstrip()
With the rstrip() method, you can eliminate trailing characters (the last characters in a
string).
By default, the following character is a space.
Syntax
string.rstrip(characters)
Parameter Values
Parameter Description
characters A choice. To eliminate leading characters from a set of characters.
At the last of the string, delete any empty spaces:
Example:
1
71/89
2
3
4
5
6
7
8
9
10
mrx = "**********BEST "
ample = mrx.rstrip()
print("Python is the", ample,"Programming Language")
Pass the value “*” in the rstrip() method:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "**********BEST "
ample = mrx.rstrip("*")
print("Python is the", ample,"Programming Language")
Take out the following characters:
Example:
1
2
3
4
5
6
72/89
7
8
9
10
mrx = "-->-->-->-->-->-->BEST>>>>>>>>>"
ample = mrx.rstrip(">")
print("Python is the", ample,"Programming Language")
Python Strings Method split()
Strings can be divided into lists utilizing the split() method.
Default separator is any empty space, but you can choose it.
Reminder: Selecting maxsplit will result in a list with the given number of elements plus
one.
Syntax
string.split(separator, maxsplit)
Parameter Values
Parameter Description
separator A separator can be chosen (optional), and by default, any whitespace will
be used for splitting the string.
maxsplit The number of splits is optional. The default value is -1, meaning all
instances will be split.
Make a list from a string, with each word appearing as an item:
Example:
1
2
3
4
5
6
7
8
73/89
9
10
mrx = "We are learning Python strings split() method"
ample = mrx.split()
print(ample)
Divide a string into a list by utilizing a comma and a space (“, “) as the delimiter.
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Python, Java, C, C++, C#, PHP"
ample = mrx.split(", ")
print(ample)
Apply the split() method to the mrx string, then utilize the join() method:
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "Python, Java, C, C++, C#, PHP"
ample = mrx.split(", ")
74/89
ample1 = "***".join(ample)
print(ample1)
In place of a separator, utilize the dollar “$” character:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Python$Java$C$C++$C#$PHP"
ample = mrx.split("$")
print(ample)
Divide the string into a list of at most 4 items:
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
mrx = "Python, Java, C, C++, C#, PHP"
# By setting the maxsplit parameter to 3, you will get a list of 4 elements!
75/89
ample = mrx.split(", ", 3)
print(ample)
# The output has four values. 'Python' is the first, 'Java' is the second, 'C' is the third,
'C++, C#, PHP' is the last.
Python Strings Method splitlines()
A string is divided into a list utilizing the splitlines() method. Line breaks are used to
divide the text.
Syntax
string.splitlines(keeplinebreaks)
Parameter Values
Parameter Description
keeplinebreaks A choice. Indicates whether line breaks should be inserted (True), or
not (False). False is the default value.
Divide a string into a list with each line representing an item:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "programming language python has the splitlines() method.nIn python it's a built-
in method"
ample = mrx.splitlines()
print(ample)
Make a list where each line is a list element from a string:
76/89
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "**nprogramming language python has the splitlines() method.tIn python it's a
built-in methodn**"
ample = mrx.splitlines()
print(ample)
Maintain the line breaks when dividing the string:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "programming language python has the splitlines() method.nIn python it's a built-
in method"
ample = mrx.splitlines(True)
print(ample)
Python Strings Method startswith()
77/89
If the string begins with the given value, the startswith() method provides True, else
False.
Syntax
string.startswith(value, start, end)
Parameter Values
Parameter Description
value It is necessary. To find out if the string begins with this value
start A choice. An integer specifying where the search should begin
end A choice. The location at which the search should terminate is an integer.
Make sure the string begins with “Greetings”:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Greetings, we are learning about the Python startswith() method"
ample = mrx.startswith("Greetings")
print(ample)
Verify that the string begins with “Greetings”:
Example:
1
2
3
78/89
4
5
6
7
8
9
10
11
mrx = "Greetings, we are learning about the Python startswith() method"
mrx = mrx.lower()
ample = mrx.startswith("Greetings")
print(ample)
Make sure position 18 to 40 begins with “lear”:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Greetings, we are learning about the Python startswith() method"
ample = mrx.startswith("lear",18, 40)
print(ample)
Python Strings Method strip()
The strip() method eliminates preceding (spaces at the beginning) and following (spaces
at the last) characters (by default, a space is the leading character).
Syntax
string.strip(characters)
Parameter Values
79/89
Parameter Description
characters A choice. Characters to eliminate as preceding/following characters.
Take out the spaces at the start and at the tail of the string:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = " BEST "
ample = mrx.strip()
print("Python is the", ample,"Programming Language")
Pass the value “*” in the rstrip() method:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "**********BEST**********"
ample = mrx.strip("*")
print("Python is the", ample,"Programming Language")
Take out the preceding and following characters:
80/89
Example:
1
2
3
4
5
6
7
8
9
10
mrx = ">"
ample = mrx.strip("")
print("Python is the", ample,"Programming Language")
Python Strings Method swapcase()
By calling the swapcase() method, you can get a string that includes all uppercase letters
transformed into lowercase letters, and the reverse.
Syntax
string.swapcase()
Parameters not required – Change the small case letters to capital case and the capital
case letters to small case:
Example:
1
2
3
4
5
6
7
8
9
81/89
10
mrx = "hApPy bIRth dAy harry"
ample = mrx.swapcase()
print(ample)
Apply the non-alphabetic characters:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "!!h@pPy bIRth d@y h@rry!!"
ample = mrx.swapcase()
print(ample)
Python Strings Method title()
The title() method generates a string with the first character in every word uppercase. It’s
like a header or a title.
Words including numbers or symbols will be transformed into uppercase after the first
letter.
Syntax
string.title()
Parameters are not required – Make sure every word begins with an uppercase letter:
Example:
1
82/89
2
3
4
5
6
7
8
9
10
mrx = "guido van rossum is the founder of Python language"
ample = mrx.title()
print(ample)
Verify that every word begins with an uppercase letter in the following example:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "GUIDO VAN ROSSUM is the founder of PYTHON language"
ample = mrx.title()
print(ample)
Ensure that the initial letter of each word is uppercase:
Example:
1
2
3
4
5
6
83/89
7
8
9
10
mrx = "**Python is the 1st easy to learn language in the world**"
ample = mrx.title()
print(ample)
In the following example, check that the initial letter after a non-alphabet letter is
changed to uppercase:
Example:
1
Python Strings Method translate()
Translate() generates a string having some chosen characters substituted with the
character stored in a dictionary or mapping table.
To make a mapping table, call the maketrans() method.
In the absence of a dictionary/table, a character will not be substituted.
In place of characters, you must utilize ASCII codes when referring to a dictionary.
Syntax
string.translate(table)
Parameter Values
Parameter Description
table This is essential. Explains how to substitute a value in a dictionary or
mapping table.
If there is a “K” letter, substitute it with a “J” letter:
Example:
84/89
1
2
3
4
5
6
7
8
9
10
11
#Utilize a dictionary with ASCII codes to substitute 75 (K) with 74 (J):
mrx_dict = {75: 74}
ample = "Greetings Kane.."
print(ample.translate(mrx_dict))
Substitute “K” with “J” through a mapping table:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "Greetings Kane.."
ample_table = mrx.maketrans("K", "J")
print(mrx.translate(ample_table))
To substitute multiple characters, utilize a mapping table:
Example:
1
2
3
85/89
4
5
6
7
8
9
10
11
12
13
mrx = "Eva"
ample1 = "aEv"
ample2 = "yAm"
mrx_table = mrx.maketrans(ample1, ample2)
print(mrx.translate(mrx_table))
You can delete characters from the string through the third parameter in the mapping
table:
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
mrx = "Bonjour Eva!!"
ample1 = "Eva"
ample2 = "Lia"
ample3 = "Bonjour"
mrx_table = mrx.maketrans(ample1, ample2, ample3)
print(mrx.translate(mrx_table))
Utilizing a dictionary rather than a mapping table, here is the same example as above:
86/89
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "Bonjour Eva!!"
ample_dict = {69: 76, 118: 105, 97: 97, 66: None, 111: None, 110: None, 106: None, 117:
None, 114: None}
print(mrx.translate(ample_dict))
Python Strings Method upper()
upper() method generates a string that contains all letters in capital case.
Numbers and symbols are not taken into account.
Syntax
string.upper()
There are no parameters – Make the string larger case:
Example:
1
2
3
4
5
6
7
8
87/89
9
10
mrx = "Welcome to PYTHON Strings upper() Method."
ample = mrx.upper()
print(ample)
Apply the digits at the beginning of the string then convert the string to capital case:
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "3.11.1 is the latest version of python!"
ample = mrx.upper()
print(ample)
Python Strings Method zfill()
The zfill() method inserts zeros (0) at the start of a string until it reaches the given
length.
There is no filling if len is smaller than the length of the string.
Syntax
string.zfill(len)
Parameter Values
Parameter Description
len This is necessary. The length of the string should be represented by a
number.
To make the string 6 characters wide, fill it with zeros:
88/89
Example:
1
2
3
4
5
6
7
8
9
10
mrx = "88"
ample = mrx.zfill(6)
print(ample)
Implement the zfill() method to string then utilize upper() method:
Example:
1
2
3
4
5
6
7
8
9
10
11
mrx = "mrexamples"
ample = mrx.zfill(15)
ample = ample.upper()
print(ample)
To make the strings various characters wide, fill them with zeros:
Example:
89/89
1
2
3
4
5
6
7
8
9
10
11
12
mrx1 = "Greetings"
mrx2 = "Python zfill() method"
mrx3 = "20499"
print(mrx1.zfill(15))
print(mrx2.zfill(9))
print(mrx3.zfill(7))
Having learned about Python strings methods and how they work, you are now
prepared to use them.

More Related Content

What's hot

Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaAbhilash Nair
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in PythonDrJasmineBeulahG
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
introduction to python
 introduction to python introduction to python
introduction to pythonJincy Nelson
 
Python - gui programming (tkinter)
Python - gui programming (tkinter)Python - gui programming (tkinter)
Python - gui programming (tkinter)Learnbay Datascience
 
python Function
python Function python Function
python Function Ronak Rathi
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data typesMohd Sajjad
 

What's hot (20)

Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Python array
Python arrayPython array
Python array
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
introduction to python
 introduction to python introduction to python
introduction to python
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Python - gui programming (tkinter)
Python - gui programming (tkinter)Python - gui programming (tkinter)
Python - gui programming (tkinter)
 
C string
C stringC string
C string
 
python Function
python Function python Function
python Function
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 

Similar to Python Strings Methods

Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3Syed Farjad Zia Zaidi
 
stringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfstringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfpaijitk
 
Python String rstrip() Method.pdf
Python String rstrip() Method.pdfPython String rstrip() Method.pdf
Python String rstrip() Method.pdfDeveloper Helps
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptxPadreBhoj
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotesSowri Rajan
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdfGaneshRaghu4
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework HelpC++ Homework Help
 
ppt notes python language operators and data
ppt notes python language operators and datappt notes python language operators and data
ppt notes python language operators and dataSukhpreetSingh519414
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxhardii0991
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 

Similar to Python Strings Methods (20)

Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3
 
stringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfstringsinpython-181122100212.pdf
stringsinpython-181122100212.pdf
 
Python String rstrip() Method.pdf
Python String rstrip() Method.pdfPython String rstrip() Method.pdf
Python String rstrip() Method.pdf
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
String handling
String handlingString handling
String handling
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Python data handling
Python data handlingPython data handling
Python data handling
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Module 3 - Regular Expressions, Dictionaries.pdf
Module 3 - Regular  Expressions,  Dictionaries.pdfModule 3 - Regular  Expressions,  Dictionaries.pdf
Module 3 - Regular Expressions, Dictionaries.pdf
 
M C6java7
M C6java7M C6java7
M C6java7
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
ppt notes python language operators and data
ppt notes python language operators and datappt notes python language operators and data
ppt notes python language operators and data
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptx
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Strings
StringsStrings
Strings
 

More from Mr Examples

Python Strings Format
Python Strings FormatPython Strings Format
Python Strings FormatMr Examples
 
Python Online Compiler
Python Online CompilerPython Online Compiler
Python Online CompilerMr Examples
 
What Is Solidity
What Is SolidityWhat Is Solidity
What Is SolidityMr Examples
 
Python Variables
Python VariablesPython Variables
Python VariablesMr Examples
 
World Environment Day 2022
World Environment Day 2022World Environment Day 2022
World Environment Day 2022Mr Examples
 
World Bee Day 2022
World Bee Day 2022World Bee Day 2022
World Bee Day 2022Mr Examples
 

More from Mr Examples (6)

Python Strings Format
Python Strings FormatPython Strings Format
Python Strings Format
 
Python Online Compiler
Python Online CompilerPython Online Compiler
Python Online Compiler
 
What Is Solidity
What Is SolidityWhat Is Solidity
What Is Solidity
 
Python Variables
Python VariablesPython Variables
Python Variables
 
World Environment Day 2022
World Environment Day 2022World Environment Day 2022
World Environment Day 2022
 
World Bee Day 2022
World Bee Day 2022World Bee Day 2022
World Bee Day 2022
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

Python Strings Methods

  • 1. 1/89 October 28, 2022 Python Strings Methods mrexamples.com/python/references/python-strings-methods Strings Methods In Python Here we learn Python strings methods in the hope that it will meet your educational needs. There are a number of Python built-in methods that can be used to manipulate strings. There is one thing to keep in mind when using string methods: they all return new values. In other words, they do not change the original string in any way. Python Strings Methods List Methods Overview capitalize() Uppercase the first character. casefold() Makes string lowercase. center() Python strings methods return centered strings. count() A string’s frequency of a particular value. encode() An encoded string is returned.
  • 2. 2/89 endswith() The string is true if it ends with the given value. expandtabs() This property specifies the string’s tab size. find() Returns the position where a specified value was found in the string in Python. format() String format for given values. format_map() String format for given values. index() Returns the point where a given value was found in the string. isalnum() True if a string contains all alphanumeric characters. isalpha() True if the string has all alphabetic characters. isdecimal() True if all characters are decimals. isdigit() Returns True if all characters in a string are digits. isidentifier() Identifies the string with True. islower() True if all characters are lowercase. isnumeric() Numeric characters in the string are returned as True. isprintable() True if the string has all printable characters. isspace() Returns True if the string contains only whitespace. istitle() True if the string follows title rules. isupper() Python strings methods return True if all characters are uppercase. join() Combines the elements of an iterable to the string’s end. ljust() The string is left justified when returned. lower() Lowers the case of a string. lstrip() The string’s left trim version is returned. maketrans() This method returns a translation table for use in translations. partition() In Python strings methods, this function returns a tuple with the string divided into three parts. replace() Returns a string in which a specified value has been replaced with another specified value. rfind() The string is searched for a specific value, and the latest location where it was found is returned. rindex() The string is searched for a specific value, and the latest location where it was found is returned.
  • 3. 3/89 rjust() Returns the string’s right justified version. rpartition() Returns a tuple with the string divided into three parts. rsplit() Returns a list after splitting the string at the provided separator. rstrip() Returns the string’s right trim version. split() Returns a list after splitting the string at the provided separator. splitlines() Returns a list after splitting the string at line breaks. startswith() If the string begins with the supplied value, this function returns true. strip() This method returns a reduced version of the string. swapcase() Cases are switched, with the lower case becoming upper case and vice versa. title() Every word’s initial character is converted to upper case. translate() This function returns a translated string. upper() This function converts a string to upper case. zfill() Fills the string at the start with a defined set of 0 values. It is imperative to note that Python strings methods return rewritten values. The original string remains unchanged. Python Strings Tutorial explains strings in more detail. Python Strings Methods Examples The following is an in-depth explanation of Python Strings Methods, with examples for each method. Python Strings Method capitalize() Capitalize() method generates a string with the first character in upper case, and the remaining characters in lower case. Syntax: string.capitalize() There are no parameters. The following sentence begins with an uppercase letter: Capitalize() Example:1
  • 4. 4/89 1 2 3 4 5 6 7 8 9 10 mrx_string = "hey!! future developers, welcome to the python strings method." ample = mrx_string.capitalize() print (ample) We convert the first character to uppercase, and the following characters to lowercase: Capitalize() Example:2 1 2 3 4 5 6 7 8 9 10 mrx_string = "python is an easiest, modern Programming Language" ample = mrx_string.capitalize() print (ample) Try it with a number as the first character: Capitalize() Example:3 1 2 3
  • 5. 5/89 4 5 6 7 8 9 10 mrx_string = "1991 was the year when the first version of Python was released." ample = mrx_string.capitalize() print (ample) As a first character, test a symbol: Capitalize() Example:4 1 2 3 4 5 6 7 8 9 10 mrx_string = "# is used as a comment symbol in Python." ample = mrx_string.capitalize() print (ample) Python Strings Method casefold() Python String Casefold() generates a string with all characters in lower case. In comparison to lower(), casefold() is better, more efficient, indicating that it will transform more characters into lower case, and will find more matches when comparing two strings transformed by casefold(). Syntax: string.casefold() There are no parameters. Change the string to lower case:
  • 6. 6/89 Casefold() Example:1 1 2 3 4 5 6 7 8 9 10 mrx_string = "Hey!! Future developers, Welcome to the Python strings method." ample = mrx_string.casefold() print(ample) Try it with a number as the first character: Casefold() Example:2 1 2 3 4 5 6 7 8 9 10 mrx_string = "1991 was the year when the First Version of Python was released." ample = mrx_string.casefold() print(ample) Python Strings Method center() Python String Center() method will position the string in the center, using a given character as fill (space by default). Syntax:
  • 7. 7/89 string.center(length, character) Parameter Values Parameter Summary length It is necessary. Provide the length of the string character A choice. Fill in the missing space on each side with this character. The default value is ” ” (empty space). In the center of the 70 characters, display the word “mrexamples”: Center() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "mrexamples" ample = mrx.center(70) print(ample) Utilizing the symbol “*” as the padding character: Center() Example:2 1 2 3 4 5 6 7 8
  • 8. 8/89 9 10 mrx = "mrexamples" ample = mrx.center(70, "*") print(ample) First implement the casefold() method to string then apply the center() method: Center() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 mrx = "MReXamples" mrx = mrx.casefold() ample = mrx.center(70, "!") print(ample) Python Strings Method count() The Count() method displays the occurrences of a given value present in the string. Syntax: string.count(value, start, end) Parameter Values Parameter Summary value This is necessary. A String. Look for the string value.
  • 9. 9/89 start A choice. It is an integer. Begin the search at this position – It is set to 0 by default. end A choice. This is an integer. You can stop the search at this position. Strings are terminated at the end by default. Find out how many times the string contains the word “python“: Count() Example:1 1 2 3 4 5 6 7 8 9 10 11 mrx = "Python is a high-level programming language and in python language we can use multiple python strings methods which can help us during python programming." mrx = mrx.casefold() ample = mrx.count("python") print(ample) From position 15 to 154, find as follows: Count() Example:2 1 2 3 4 5 6 7 8 9
  • 10. 10/89 10 mrx = "Python is a high-level programming language and in python language we can use multiple python strings methods which can help us during python programming." ample = mrx.count("python",15,154) print(ample) First apply the capitalize() method to the string then utilize the count() method: Count() Example:3 1 2 3 4 5 6 7 8 9 10 11 mrx = "python is a high-level programming language and in python language we can use multiple python strings methods which can help us during python programming." mrx = mrx.capitalize() ample = mrx.count("python",0,60) print(ample) Python Strings Method encode() The Encode() method encodes a string with the given encoding. In the absence of an encoding standard, UTF-8 will be utilized. Syntax: string.encode(encoding=encoding, errors=errors) Parameter Values Parameter Summary encoding A choice. Indicates the encoding to be used. The default character encoding is UTF-8
  • 11. 11/89 errors The optional part. Indicates the error method in a string. The following values are legal: ‘backslashreplace’ Replace the unencoded character with a backslash ‘ignore’ Pass over unencoded characters ‘namereplace’ Put a description of the character in place of the character ‘strict’ Failure throws an exception by default ‘replace’ A question mark appears instead of the character ‘xmlcharrefreplace’ An XML character is substituted for the character Using UTF-8, encode the string as follows: Encode() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "Python pronunciation: ˈpīˌTHän" ample = mrx.encode() print(ample) The following examples use ASCII encoding and a character that is unable to be encoded, displaying various errors: Encode() Example:2 1 2 3 4
  • 12. 12/89 5 6 7 8 9 10 11 12 mrx = "Python pronunciation: ˈpīˌTHän" print(mrx.encode(encoding="ascii",errors="backslashreplace")) print(mrx.encode(encoding="ascii",errors="ignore")) print(mrx.encode(encoding="ascii",errors="namereplace")) print(mrx.encode(encoding="ascii",errors="replace")) print(mrx.encode(encoding="ascii",errors="xmlcharrefreplace")) Implement the center() method to the string then utilize the encode() method to display the various errors of the characters that are not able to encode. Encode() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 mrx = "ⓜⓡⓧⓔⓧⓐⓜⓟⓛⓔ" print(mrx.center(70, "*")) print(mrx.encode(encoding="ascii",errors="backslashreplace")) print(mrx.encode(encoding="ascii",errors="ignore")) print(mrx.encode(encoding="ascii",errors="namereplace")) print(mrx.encode(encoding="ascii",errors="replace")) print(mrx.encode(encoding="ascii",errors="xmlcharrefreplace"))
  • 13. 13/89 Python Strings Method endswith() When the string ends with the given value, the endswith() method provides True, else False. Syntax: string.endswith(value, start, end) Parameter Values Parameter Summary value This is necessary. Verify if the string ends with. start This is optional. The location at which to begin the search as an integer. end A choice. Indicates where to end the look for as an integer. If there is a punctuation mark (?) at the end of the string, verify it: Endswith() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "Do you know about python strings method?" ample = mrx.endswith("?") print(ample) If the string ends with “method?” verify the following: Endswith() Example:2 1
  • 14. 14/89 2 3 4 5 6 7 8 9 10 mrx = "Do you know about python strings method?" ample = mrx.endswith("method?") print(ample) If position 0 to 14 ends with “Python strings methods?“, verify the following: Endswith() Example:3 1 2 3 4 5 6 7 8 9 10 mrx = "Do you know about python strings method?" ample = mrx.endswith("python strings method?", 0, 14) print(ample) Encode the string message utilizing the encode() method then apply the endswith() method to verify the string ends with “python strings methods?”: Endswith() Example:4 1 2 3 4 5
  • 15. 15/89 6 7 8 9 10 11 12 mrx = "Do you know about python strings methods?" print(mrx.encode()) ample = mrx.endswith("python strings methods?", 0, len(mrx)) print(ample) Python Strings Method expandtabs() By calling the expandtabs() method, the tab size is set to the number of whitespaces given. Syntax: string.expandtabs(tabsize) Parameter Values Parameter Summary tabsize A choice. A number indicating the tabsize – Tabsize is set to 8 by default To set the tab size to three blank spaces: Expandtabs() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "MtRt.tEtXtAtMtPtLtE"
  • 16. 16/89 ample = mrx.expandtabs(4) print(ample) Apple the casefold() method and count() method then set the tab size to four blank spaces: Expandtabs() Example:2 1 2 3 4 5 6 7 8 9 10 11 12 mrx = "MtRt.tEtXtAtMtPtLtE" mrx = mrx.casefold() print(mrx.count("t")) ample = mrx.expandtabs(4) print(ample) Utilizing various tab sizes, you can examine the results: Expandtabs() Example:3 1 2 3 4 5 6 7 8 9 10 11
  • 17. 17/89 12 13 mrx = "MtRt.tEtXtAtMtPtLtE" print(mrx) print(mrx.expandtabs()) print(mrx.expandtabs(2)) print(mrx.expandtabs(4)) print(mrx.expandtabs(6)) print(mrx.expandtabs(10)) Python Strings Method find() The find() method locates the initial appearance of the given value. If the value cannot be located, find() method displays -1. There is only one difference between the find() method and the index() method. If the value cannot be found, the index() method throws an error. (Refer to the below example) Syntax string.find(value, start, end) Parameter Values Parameter Summary value This is necessary. A String. Look for the string value. start A choice. Begin the search at this position. It is set to 0 by default. end A choice. You can stop the search at this position. Strings are terminated at the end by default. What is the location of the word “python” in the text? : Find() Example:1 1 2 3 4 5 6
  • 18. 18/89 7 8 9 10 mrx = "Hey future developer!, welcome to the python string find() method." ample = mrx.find("python") print(ample) What is the first appearance of “r” in the text? : Find() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = "Hey future developer!, welcome to the python string find() method." ample = mrx.find("r") print(ample) If you only search between positions 20 and len(mrx), where is the first appearance of the character “r“? : Find() Example:3 1 2 3 4 5 6 7 8 9 10
  • 19. 19/89 mrx = "Hey future developer!, welcome to the python string find() method." ample = mrx.find("r", 20, len(mrx)) print(ample) The find() method returns -1 if the value could not be located, but the index() method will throw an error: Find() Example:4 1 2 3 4 5 6 7 8 9 mrx = "Hey future developer!, welcome to the python string find() method." print(mrx.find("z")) #returns -1 print(mrx.index("z")) #throws an exception Capitalize the string first, utilize the count() method to the capitalized string then apply the find() method: Find() Example:5 1 2 3 4 5 6 7 8 9 10 11 12 mrx = "hey future developer!, welcome to the python string find() method." mrx = mrx.capitalize()
  • 20. 20/89 print(mrx) print(mrx.count("H")) ample = mrx.find("h") print(ample) Python Strings Method format() The Format() method formats the given value(s) and adds them to the string’s placeholder. Curly brackets are utilized to identify the placeholder: {}. In the Placeholder area below, you can learn a lot about placeholders. The format() method provides a well-formatted string. Syntax string.format(value1, value2...) Parameter Values Parameter Summary value1, value2… It is necessary. In the string, one or several values must be formatted and added. It can also be a list of items divided by commas, a key-value list, or a mixture of both. Any data type can be utilized for the values. Place the net_worth in the placeholder, in three-digit fixed point form: Format() Example:1 1 2 3 4 5 6 7
  • 21. 21/89 8 mrx = "The net worth of Bernard Arnault is $164.000 billion" print(mrx.format(net_worth = 164)) Placeholders It is feasible to recognize the placeholders based on their names {net_worth}, numbers {0}, or possibly by empty placeholders {}. Placing a variety of placeholder values: Placeholder Example:1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #Indexed with names: mrx1 = "Name: {name}, Age: {age}, Residence: {res}, Net worth: {n_worth}".format(name = "Elon Musk", age = 51, res = "Texas", n_worth = "$128 billion") #Indexed with numbers: mrx2 = "Name: {0}, Age: {1}, Residence: {2}, Net worth: {3}".format("Bill Gates", 67, "Washington", "$109 billion") #Placeholders that are void: mrx3 = "Name: {}, Age: {}, Residence: {}, Net worth: {}".format("Jeff Bezos", 58, "Washington", "$109 billion") print(mrx1) print(mrx2) print(mrx3)
  • 22. 22/89 Utilize the center() method to display the “Billionaires” string in the center and place a variety of placeholder values. In the last step, apply the capitalize(), casefold() and find() methods to the strings: Placeholder Example:2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #Indexed with names: print("Billionaires".center(70)) mrx1 = "Name: {name}, Age: {age}, Residence: {res}, Net worth: {n_worth}".format(name = "Elon Musk", age = 51, res = "Texas", n_worth = "$128 billion") #Indexed with numbers: mrx2 = "Name: {0}, Age: {1}, Residence: {2}, Net worth: {3}".format("Bill Gates", 67, "Washington", "$109 billion") #Placeholders that are void: mrx3 = "Name: {}, Age: {}, Residence: {}, Net worth: {}".format("Jeff Bezos", 58, "Washington", "$109 billion") print(mrx1.capitalize()) print(mrx2.casefold()) print(mrx3.find("Washington")) Formatting Types Insert a formatting type within the placeholders to format the output: :< Position the results to the left (using free space).
  • 23. 23/89 :> Position the results to the right (using free space). :^ Position the results to the center (using free space). := Orient the sign to the left :+ To represent a positive or negative outcome, utilize a plus sign :- You must write a minus sign for negative values : To precede positive numbers, add a space (and to precede negative numbers, a minus sign). :, As a thousand separator, utilize a comma :_ In place of a thousand separator, utilize an underscore :b Binary format :c Obtain the corresponding Unicode character from the value :d Decimal format :e Utilizing a smaller case e in scientific format :E Utilizing a larger case E in scientific format :f Correct point number format :F Format point numbers in uppercase (show infs and nans as INFs and NANS) :g General format :G For scientific notation, utilize an uppercase E. Octal format Hex format, smaller case :X Hex format, larger case :n Number format :% Percentage format Python Strings Method index() By calling the index() method, you can locate the first appearance of a value you provide. If the value cannot be located, index() throws an error. The index() method is almost identical to the find() method, with the exception that the find() method provides -1 if no value is located. (Check out the example below)
  • 24. 24/89 Syntax string.index(value, start, end) Parameter Values Parameter Summary value This is necessary. A String. Look for the string value. start A choice. Begin the search at this position. It is set to 0 by default. end A choice. You can stop the search at this position – Strings are terminated at the end by default. What is the location of the word “python” in the text? : Index() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "Hey future developer!, welcome to the python string index() method." ample = mrx.index("python") print(ample) What is the first appearance of “r” in the text? : Index() Example:2
  • 25. 25/89 1 2 3 4 5 6 7 8 9 10 mrx = "Hey future developer!, welcome to the python string index() method." ample = mrx.index("r") print(ample) If you only search between positions 20 and len(mrx), where is the first appearance of the character “r”? : Index() Example:3 1 2 3 4 5 6 7 8 9 10 mrx = "Hey future developer!, welcome to the python string index() method." ample = mrx.index("r", 20, len(mrx)) print(ample) The find() method returns -1 if the value could not be located, but the index() method will throw an error: Index() Example:4 1 2
  • 26. 26/89 3 4 5 6 7 8 9 mrx = "Hey future developer!, welcome to the python string index() method." print(mrx.index("z")) #throws an exception print(mrx.find("z")) #returns -1 Capitalize the string first, utilize the count() method to the capitalized string then apply the index() method: Index() Example:5 1 2 3 4 5 6 7 8 9 10 11 12 mrx = "hey future developer!, welcome to the python string index() method." mrx = mrx.capitalize() print(mrx) print(mrx.count("H")) ample = mrx.index("h") print(ample) Python Strings Method isalnum() When all the characters are letters (a-z) and digits (0-9), then the isalnum() method produces True. Non-alphanumeric characters: (space)!#%&? etc.
  • 27. 27/89 Syntax string.isalnum() Parameters are not required – Make sure each of the characters in the string is alphanumeric: Isalnum() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "Nimbus2000" ample = mrx.isalnum() print(ample) Verify that each of the characters in the string is alphanumeric: Isalnum() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = "iPhone 14" ample = mrx.isalnum() print(ample)
  • 28. 28/89 Apply the underscore to the alphanumeric string: Isalnum() Example:3 1 2 3 4 5 6 7 8 9 10 mrx = "iPhone_14" ample = mrx.isalnum() print(ample) Python Strings Method isascii() If each of the characters are ASCII characters, the isascii() method displays True. Syntax string.isascii() Parameters are not required – Make sure each of the characters in the string is ASCII: Isascii() Example:1 1 2 3 4 5 6 7 8 9
  • 29. 29/89 10 mrx = "Rain, snow, mud, and off-road conditions are no problem for the Model Y of Tesla." ample = mrx.isascii() print(ample) Verify that each character in the mrx string is ASCII: Isascii() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = "Python pronunciation: ˈpīˌTHän" ample = mrx.isascii() print(ample) Python Strings Method isdecimal() If each of the characters is a decimal (0-9), the isdecimal() method outputs True. Unicode objects utilize this method. Syntax string.isdecimal() Parameters are not required – Verify that all the characters in the Unicode object are decimal: Isdecimal() Example:1 1
  • 30. 30/89 2 3 4 5 6 7 8 9 10 mrx = "u0039" #unicode for 9 ample = mrx.isdecimal() print(ample) Make sure that each of the characters in Unicode are decimals: Isdecimal() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = "u0036" #unicode for 6 ample = "u0041" #unicode for A print(mrx.isdecimal()) print(ample.isdecimal()) Ensure that each Unicode character is a decimal: Isdecimal() Example:3 1 2 3 4 5
  • 31. 31/89 6 7 8 9 10 11 12 mrx1 = "u0038" #unicode for 8 mrx2 = "u0048" #unicode for H mrx3 = "u005F" #unicode for underscore(_) print(mrx1.isdecimal()) print(mrx2.isdecimal()) print(mrx3.isdecimal()) Python Strings Method isdigit() If each and every character is digits, the isdigit() method provides True, else False. Numbers with exponents, such as ², are also regarded as digits. Syntax string.isdigit() Parameters are not required – Verify that all of the string characters are numbers: Isdigit() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "7800000" ample = mrx.isdigit() print(ample)
  • 32. 32/89 First, separate the thousand by an underscore, then verify that all string characters are digits: Isdigit() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = "10_000_000" ample = mrx.isdigit() print(ample) Prove that all of the string characters are numbers: Isdigit() Example:3 1 2 3 4 5 6 7 8 9 10 mrx = "u0039" #unicode for 9 ample = "u00B3" #unicode for ³ print(mrx.isdigit()) print(ample.isdigit()) Python Strings Method isidentifier()
  • 33. 33/89 If the string is a correct identifier, isidentifier() provides True, else False. Strings with only alphanumeric characters (a-z) and zero through nine, or underscores (_), are accepted as correct identifiers. A correct identifier cannot begin with a number or include any spaces. Syntax string.isidentifier() Parameters are not required – Verify that the string is a correct identifier: Isidentifier() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "mrexamples" ample = mrx.isidentifier() print(ample) Make sure the string is the correct identifier: Isidentifier() Example:2 1 2 3 4 5 6 7 8
  • 34. 34/89 9 10 mrx = "isidentifier_Method" ample = mrx.isidentifier() print(ample) To find out if the strings are correct identifiers, check the following: Isidentifier() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 mrx1 = "mrx-1" mrx2 = "Mrx1" mrx3 = "1ample" mrx4 = "ample one" mrx5 = "Mrx_1" mrx6 = "@mple" print(mrx1.isidentifier()) print(mrx2.isidentifier()) print(mrx3.isidentifier()) print(mrx4.isidentifier()) print(mrx5.isidentifier()) print(mrx6.isidentifier())
  • 35. 35/89 Python Strings Method islower() If all the letters are in small case, the islower() method outputs True, else outputs False. Only alphabetic characters are validated, not numbers, symbols, or spaces. Syntax string.islower() There are no parameters – Make sure all the letters in the string are lowercase: Islower() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "hey!! future developers, welcome to the python string islower() method." ample = mrx.islower() print(ample) If the first character in a string is a digit, ensure that all the characters are in lower case: Islower() Example:2 1 2 3 4 5 6 7 8
  • 36. 36/89 9 mrx = "1991 was the year when the first version of python was released." ample = mrx.islower() print(ample) Verify that all the letters in the multiple strings are in smaller case: Islower() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 mrx1 = "mr_examples" mrx2 = "iphone 14" mrx3 = "Steve Jobs is the owner of the Apple company" mrx4 = "iphoneX" print(mrx1.islower()) print(mrx2.islower()) print(mrx3.islower()) print(mrx4.islower()) Python Strings Method isnumeric() When all characters (0-9 are numeric), isnumeric() provides True, else it gives False. Numerical values include exponents, such as ⁷ and ¾. “-7” and “4.5” are unable to be accepted as numeric values, because every characters in the string have to be numeric, and the – and “.” are not. Syntax
  • 37. 37/89 string.isnumeric() Parameters are not required – Verify that all of the string characters are numeric: Isnumeric() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "2³" ample = mrx.isnumeric() print(ample) First, separate the thousand by a comma in the string, then verify that all string characters are numeric: Isnumeric() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = "48,000,000" ample = mrx.isnumeric() print(ample) Make sure the characters are in numeric form:
  • 38. 38/89 Isnumeric() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 mrx1 = "u0039" #unicode for 9 mrx2 = "u00B3" #unicode for ³ mrx3 = "90mph" mrx4 = "3.67" mrx5 = "-7" mrx6 = "7¾" print(mrx1.isnumeric()) print(mrx2.isnumeric()) print(mrx3.isnumeric()) print(mrx4.isnumeric()) print(mrx5.isnumeric()) print(mrx6.isnumeric()) Python Strings Method isprintable() Isprintable() returns True if all characters are printable, otherwise False. In addition to carriage returns and line breaks, there are several non-printable characters. Syntax string.isprintable()
  • 39. 39/89 Parameters are not required – Verify that all of the string characters are printable: Isprintable() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "Tesla latest model: Model Y" ample = mrx.isprintable() print(ample) Make sure the string is printable by checking the following: Isprintable() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = "Tesla latest model:tModel Y" ample = mrx.isprintable() print(ample) Ensure that all the characters in the string are printable: Isprintable() Example:3
  • 40. 40/89 1 2 3 4 5 6 7 8 9 10 mrx = "#Tesla latest model:nModel Y" ample = mrx.isprintable() print(ample) Python Strings Method isspace() If all the characters in a string are empty spaces, the isspace() method returns True, while it returns False. Syntax string.isspace() Parameters are not required – Make sure all the characters in the string are empty spaces: Isspace() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = " " ample = mrx.isspace() print(ample)
  • 41. 41/89 Verify that all the characters in the string are blank spaces: Isspace() Example:2 1 2 3 4 5 6 7 8 9 10 mrx = " MRX " ample = mrx.isspace() print(ample) Find out that all the characters in the string are empty spaces: Isspace() Example:3 1 2 3 4 5 6 7 8 9 10 mrx = "Mr examples" ample = mrx.isspace() print(ample) Python Strings Method istitle()
  • 42. 42/89 When all words in a text have an uppercase letter and the remainder are lowercase letters, the istitle() method provides True; else, it provides False. It is not necessary to include symbols or numbers. Syntax string.istitle() Parameters are not required – Make sure every word begins with an uppercase letter: Istitle() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "Guido Van Rossum Is The Founder Of Python Language" ample = mrx.istitle() print(ample) Verify that every word begins with an uppercase letter in the following example: Istitle() Example:2 1 2 3 4 5 6 7 8 9 10
  • 43. 43/89 mrx = "Guido Van Rossum Is The Founder Of PYTHON Language" ample = mrx.istitle() print(ample) In the following example, ensure that each word in the string begins with an uppercase letter: Example: 1 Python Strings Method isupper() If all the letters are in larger case, the isupper() method outputs True, else outputs False. Only alphabetic characters are validated, not numbers, symbols, or spaces. Syntax string.isupper() There are no parameters – Make sure all the letters in the string are uppercase: Isupper() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "HELLO PYTHON DEVELOPERS!!" ample = mrx.isupper() print(ample) If the first character in a string is a digit, ensure that all the characters are in upper case:
  • 44. 44/89 Isupper() Example:2 1 2 3 4 5 6 7 8 9 mrx = "1991 WAS THE YEAR WHEN THE FIRST VERSION OF PYTHON WAS RELEASED." ample = mrx.isupper() print(ample) Verify that all the letters in the multiple strings are in larger case: Isupper() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 mrx1 = "MR_EXAMPLES" mrx2 = "IPHONE 14" mrx3 = "Steve Jobs is the owner of the Apple company" mrx4 = "iPHONE 14 PRO MAX" print(mrx1.isupper()) print(mrx2.isupper())
  • 45. 45/89 print(mrx3.isupper()) print(mrx4.isupper()) Python Strings Method join() In the join() method, each of the elements in an iterable is joined into a single string. As a separator, you have to provide a string. Syntax string.join(iterable) Parameter Values Parameter Summary iterable It is necessary. If all the retrieved items are strings, then the iterable object is String. By applying a ” –> ” as a separator, join all elements in a tuple into a string: Join() Example:1 1 2 3 4 5 6 7 8 9 10 digit_tuple = ("1", "2", "3", "4", "5") mrx = " --> ".join(digit_tuple) print(mrx) Utilize a “n” as a separator, join all elements in a tuple into a string: Join() Example:2
  • 46. 46/89 1 2 3 4 5 6 7 8 9 10 digit_tuple = ("1", "2", "3", "4", "5") mrx = "n".join(digit_tuple) print(mrx) Create a string by connecting all entries in a dictionary with the word “TRY” as a separating word: Join() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 bio_dict = {"name": "Harry", "age":19, "profession": "Football", "country": "United Sates of America"} separate_by = "TRY" mrx = separate_by.join(bio_dict) print(mrx) Reminder: As an iterable, a dictionary displays the keys, not the values. Python Strings Method ljust()
  • 47. 47/89 By calling the ljust() method, a chosen character (space by default) will be assigned as the fill character of the string. Syntax string.ljust(length, character) Parameter Values Parameter Summary length This is necessary. Provides the length of the string. character A choice. To occupy the blank space (to the right of the string), enter a character. The default value is ” ” (space). By applying a ” –> ” as a separator, join all elements in a tuple into a string: ljust() Example:1 1 2 3 4 5 6 7 8 9 10 mrx = "Python" ample = mrx.ljust(35) print(ample, "is the easiest programming language.") Utilize a “n” as a separator, join all elements in a tuple into a string: ljust() Example:2 1
  • 48. 48/89 2 3 4 5 6 7 8 9 10 mrx = "PYTHON" ample = mrx.ljust(50, "*") print(ample) Create a string by connecting all entries in a dictionary with the word “TRY” as a separating word: ljust() Example:3 1 2 3 4 5 6 7 8 9 10 11 12 13 bio_dict = {"name": "Harry", "age":19, "profession": "Football", "country": "United Sates of America"} separate_by = "TRY" mrx = separate_by.join(bio_dict) print(mrx) Python Strings Method lower() lower() method generates a string that contains all letters in small case. Numbers and symbols are not taken into account.
  • 49. 49/89 Syntax string.lower() There are no parameters – Make the string smaller case: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Welcome to PYTHON Strings lower() Method." ample = mrx.lower() print(ample) Apply the digits at the beginning of the string then convert the string to small case: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "3.11.1 is the latest version of PYTHON!" ample = mrx.lower() print(ample)
  • 50. 50/89 Python Strings Method lstrip() lstrip() eliminates any preceding characters (the space character is the default preceding character). Syntax string.ljust(length, character) Parameter Values Parameter Description characters A choice. To eliminate as main characters a set of characters. Left-justify the string by eliminating spaces: Example: 1 2 3 4 5 6 7 8 9 10 mrx = " BEST>>>>>>>>>" ample = mrx.lstrip() print("Python is the", ample,"Programming Language") Pass the value “>” in the lstrip() method: Example: 1 2 3 4
  • 51. 51/89 5 6 7 8 9 10 mrx = " BEST>>>>>>>>>" ample = mrx.lstrip(">") print("Python is the", ample,"Programming Language") Take out the preceding characters: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "-->-->-->-->-->-->BEST>>>>>>>>>" ample = mrx.lstrip("->") print("Python is the", ample,"Programming Language") Python Strings Method maketrans() Maketrans() method provides a mapping table that can be utilized with the translate() method to substitute selected characters. Syntax string.maketrans(x, y, z) Parameter Values Parameter Description
  • 52. 52/89 x This is necessary. A dictionary explaining how to execute the substitution must be given if only one parameter is given. A string indicating the characters to substitute must be given if two or more parameters are given. y A choice. The length of the string is the same as the parameter x. In this string, every character in the initial parameter will be substituted with its equivalent character. z A choice. Indicates which characters must be deleted from the original string. Utilize the mapping table in the translate() method to substitute any “G” characters for “H” characters: Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "Garry: We are learning python string maketrans() methods" ample = mrx.maketrans("G", "H") print(ample) #showing decimal number of ASCII characters G and H print(mrx.translate(ample)) Initially implement the lower() method on string, then apply the maketrans() method: Example: 1 2 3 4 5
  • 53. 53/89 6 7 8 9 10 11 12 mrx = "KANE: We are learning Python String Methods" mrx = mrx.lower() ample = mrx.maketrans("k", "j") print(mrx.translate(ample)) To substitute multiple characters, utilize a mapping table: Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 mrx = "Eva" ample1 = "aEv" ample2 = "yAm" mrx_table = mrx.maketrans(ample1, ample2) print(mrx.translate(mrx_table)) You can delete characters from the string through the third parameter in the mapping table: Example: 1
  • 54. 54/89 2 3 4 5 6 7 8 9 10 11 12 13 14 mrx = "Bonjour Eva!!" ample1 = "Eva" ample2 = "Lia" ample3 = "Bonjour" mrx_table = mrx.maketrans(ample1, ample2, ample3) print(mrx.translate(mrx_table)) In Unicode, the maketrans() method generates a dictionary explaining each substitution: Example: 1 2 3 4 5 6 7 8 9 10 11 12 mrx = "Bonjour Eva!!" ample1 = "Eva" ample2 = "Lia" ample3 = "Bonjour" print(mrx.maketrans(ample1, ample2, ample3))
  • 55. 55/89 Python Strings Method partition() Through the partition() method, you can look for a string and divide it into tuples with three elements. In the first element, the part preceding the given string is included. The string mentioned in the second element can be found in the second element. After the string, the third element includes the part. Reminder: This method finds the initial appearance of the given string. Syntax string.partition(value) Parameter Values Parameter Description value It is necessary. Specify the search string Provide a tuple with three elements that include the word “partition()“: 1. Anything that precedes “equivalent” 2. The “equivalent” 3. Anything that follows “equivalent” Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Python Strings partition() Method" ample = mrx.partition(" partition() ") print(ample)
  • 56. 56/89 Apply the title() method to the mrx string, then utilize the partition() method: Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "python strings method" mrx = mrx.title() ample = mrx.partition("Strings") print(ample) Partition() method generates a tuple with: first the whole string, second an unfilled string, third an unfilled string if the given value is not present: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Python Strings partition() Method" ample = mrx.partition("maketrans()") print(ample)
  • 57. 57/89 Python Strings Method replace() By calling the replace() method, you can substitute a phrase for a new phrase. Reminder: A substitution will be executed on all occurrences of the given phrase if nothing else is provided. Syntax string.replace(oldvalue, newvalue, count) Parameter Values Parameter Description oldvalue It is necessary. Specify the search string newvalue This is necessary. Replacement string for the previous value count A choice. The number of instances of the previous value you want to replace. All instances are set to default. Substitute “3.8.0” to “3.11.1”: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Latest version of Python is 3.8.0" ample = mrx.replace("3.8.0", "3.11.1") print(ample) Utilize the replace() method on a string, then implement the partition() method: Example:
  • 58. 58/89 1 2 3 4 5 6 7 8 9 10 11 txt = "Black…White…Blue" x = txt.replace("…", "") ample = x.partition("White") print(ample) Change all appearances of “two” to “nine”: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "The net worth of Bill Gates is one hundred two billion dollars, and Jeff Bezos is also one hundred two billion dollars." ample = mrx.replace("two", "nine") print(ample) Change the first appearance of the word “two” to “nine”: Example: 1
  • 59. 59/89 2 3 4 5 6 7 8 9 10 mrx = "The net worth of Bill Gates is one hundred two billion dollars, and Jeff Bezos is also one hundred two billion dollars." ample = mrx.replace("two", "nine", 1) print(ample) Python Strings Method rfind() rfind() method locates the last appearance of a value. A value cannot be located if the rfind() method returns -1. The rfind() method is nearly identical to the rindex() method. You can see an example below. Syntax string.rfind(value, start, end) Parameter Values Parameter Description value It is necessary. Specify the search string. start A choice. Searching for where to begin. It is set to 0 by default. end A choice. End the search here. As default, it ends at the last. In what part of the text does the string “language” occur at the end? : Example: 1 2
  • 60. 60/89 3 4 5 6 7 8 9 10 mrx = "Python is an easy to learn language but it is also a vast language" ample = mrx.rfind("language") print(ample) Utilize the count() method on a string, then apply the rfind() method: Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "Python is an easy to learn language but it is also a vast language" print(mrx.count("language")) ample = mrx.rfind("language") print(ample) In the string where is the last appearance of the character “o”? : Example: 1 2 3 4 5
  • 61. 61/89 6 7 8 9 10 mrx = "Greetings, we are learning about the Python rfind() method" ample = mrx.rfind("o") print(ample) When you only find between positions 0 and 36, where is the final appearance of the character “t”? : Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Greetings, we are learning about the Python rfind() method" ample = mrx.rfind("t", 0, 36) print(ample) The rfind() method provides -1 if the value cannot be located, but the rindex() method throws an error if the value cannot be found: Example: 1 2 3 4 5 6 7 8
  • 62. 62/89 9 mrx = "Greetings, we are learning about the Python rfind() method" print(mrx.rfind("x")) print(mrx.rindex("x")) Python Strings Method rindex() The rindex() method searches for the last instance of a given value. If the value is not found, an error will occur. It is essentially identical to the rfind() method- please refer to the example for more information. Syntax string.rindex(value, start, end) Parameter Values Parameter Description value It is necessary. Specify the search string. start A choice. Searching for where to begin. It is set to 0 by default. end A choice. End the search here. As default, it ends at the last. In what part of the text does the string “language” occur at the end? : Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Python is an easy to learn language but it is also a vast language"
  • 63. 63/89 ample = mrx.rindex("language") print(ample) Utilize the count() method on a string, then apply the rindex() method: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Python is an easy to learn language but it is also a vast language" print(mrx.count("language")) ample = mrx.rindex("language") print(ample) In the string where is the last appearance of the character “o”? : Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Greetings, we are learning about the Python rfind() method" ample = mrx.rfind("o") print(ample) When you only find between positions 0 and 36, where is the final appearance of the character “t”? :
  • 64. 64/89 Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Greetings, we are learning about the Python rindex() method" ample = mrx.rindex("t", 0, 36) print(ample) The rfind() method provides -1 if the value cannot be located, but the rindex() method throws an error if the value cannot be found: Example: 1 2 3 4 5 6 7 8 9 mrx = "Greetings, we are learning about the Python rindex() method" print(mrx.rindex("x")) print(mrx.rfind("x")) Python Strings Method rjust() The rjust() method aligns text to the right side of a string, utilizing either a space or a given character as padding.
  • 65. 65/89 Syntax string.rjust(length, character) Parameter Values Parameter Description length This is necessary. Provides the length of the string character A choice. To occupy the blank space (to the left of the string), enter a character. The default value is ” ” (space). Provide a right-aligned 35-character representation of “Python”: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Python" ample = mrx.rjust(35) print(ample, "is the easiest programming language.") As a padding character, utilize the symbol “*”: Example: 1 2 3 4 5 6
  • 66. 66/89 7 8 9 10 mrx = "PYTHON" ample = mrx.rjust(50, "*") print(ample) For a padding character, apply the symbols “>” and “<“: Example: 1 2 3 4 5 6 mrx1 = "String " mrx2 = "rjust() " ample1 = mrx1.rjust(30, ">") ample2 = mrx2.rjust(30, " Python Strings Method rpartition() The rpartition() method looks for the final instance of a given string, which it then divides into a tuple of three elements: The part before the string, the string itself, and the part after it. Syntax string.rpartition(value) Parameter Values Parameter Description value It is necessary. Specify the search string. Provide a tuple with three elements that include the word “rpartition()“: 1 – Anything that precedes “equivalent” 2 – the “equivalent” 3 – Anything that follows “equivalent”
  • 67. 67/89 Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Programming language Python has the rpartition() method. In Python it's a built- in method" ample = mrx.rpartition("Python") print(ample) Apply the title() method to the mrx string, then utilize the rpartition() method: Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "programming language python has the rpartition() method. In python it's a built- in method" mrx = mrx.title() ample = mrx.rpartition("Python") print(ample) The rpartition() method generates a tuple with: first an unfilled string, second an unfilled string if the given value is not present, third the whole string:
  • 68. 68/89 Example: 1 2 3 4 5 6 7 8 9 10 mrx = "programming language python has the rpartition() method. In python it's a built- in method" ample = mrx.rpartition("rfind()") print(ample) Python Strings Method rsplit() The rsplit() method will separate a string into a list beginning from the right, unless the “max” parameter is set. It results in the same outcome as the split() function. Reminder: When maxsplit is given, the resulting list can include up to that many elements plus one. Syntax string.rsplit(separator, maxsplit) Parameter Values Parameter Description separator A separator can be chosen (optional), and by default, any whitespace will be used for splitting the string. maxsplit The number of splits is optional. The default value is -1, meaning all instances will be split. Divide a string into a list by utilizing a comma and a space (“, “) as the delimiter. Example:
  • 69. 69/89 1 2 3 4 5 6 7 8 9 10 mrx = "Python, Java, C, C++, C#, PHP" ample = mrx.rsplit(", ") print(ample) Apply the rsplit() method to the mrx string, then utilize the join() method: Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "Python, Java, C, C++, C#, PHP" ample = mrx.rsplit(", ") ample1 = "–".join(ample) print(ample1) Divide the string into a list of at most 4 items: Example: 1
  • 70. 70/89 2 3 4 5 6 7 8 9 10 11 12 13 14 mrx = "Python, Java, C, C++, C#, PHP" # By setting the maxsplit parameter to 3, you will get a list of 4 elements! ample = mrx.rsplit(", ", 3) print(ample) # The output has four values. 'Python, Java, C' is the first, 'C++' is the second, 'C#' is the third, 'PHP' is the last. Python Strings Method rstrip() With the rstrip() method, you can eliminate trailing characters (the last characters in a string). By default, the following character is a space. Syntax string.rstrip(characters) Parameter Values Parameter Description characters A choice. To eliminate leading characters from a set of characters. At the last of the string, delete any empty spaces: Example: 1
  • 71. 71/89 2 3 4 5 6 7 8 9 10 mrx = "**********BEST " ample = mrx.rstrip() print("Python is the", ample,"Programming Language") Pass the value “*” in the rstrip() method: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "**********BEST " ample = mrx.rstrip("*") print("Python is the", ample,"Programming Language") Take out the following characters: Example: 1 2 3 4 5 6
  • 72. 72/89 7 8 9 10 mrx = "-->-->-->-->-->-->BEST>>>>>>>>>" ample = mrx.rstrip(">") print("Python is the", ample,"Programming Language") Python Strings Method split() Strings can be divided into lists utilizing the split() method. Default separator is any empty space, but you can choose it. Reminder: Selecting maxsplit will result in a list with the given number of elements plus one. Syntax string.split(separator, maxsplit) Parameter Values Parameter Description separator A separator can be chosen (optional), and by default, any whitespace will be used for splitting the string. maxsplit The number of splits is optional. The default value is -1, meaning all instances will be split. Make a list from a string, with each word appearing as an item: Example: 1 2 3 4 5 6 7 8
  • 73. 73/89 9 10 mrx = "We are learning Python strings split() method" ample = mrx.split() print(ample) Divide a string into a list by utilizing a comma and a space (“, “) as the delimiter. Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Python, Java, C, C++, C#, PHP" ample = mrx.split(", ") print(ample) Apply the split() method to the mrx string, then utilize the join() method: Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "Python, Java, C, C++, C#, PHP" ample = mrx.split(", ")
  • 74. 74/89 ample1 = "***".join(ample) print(ample1) In place of a separator, utilize the dollar “$” character: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Python$Java$C$C++$C#$PHP" ample = mrx.split("$") print(ample) Divide the string into a list of at most 4 items: Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 mrx = "Python, Java, C, C++, C#, PHP" # By setting the maxsplit parameter to 3, you will get a list of 4 elements!
  • 75. 75/89 ample = mrx.split(", ", 3) print(ample) # The output has four values. 'Python' is the first, 'Java' is the second, 'C' is the third, 'C++, C#, PHP' is the last. Python Strings Method splitlines() A string is divided into a list utilizing the splitlines() method. Line breaks are used to divide the text. Syntax string.splitlines(keeplinebreaks) Parameter Values Parameter Description keeplinebreaks A choice. Indicates whether line breaks should be inserted (True), or not (False). False is the default value. Divide a string into a list with each line representing an item: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "programming language python has the splitlines() method.nIn python it's a built- in method" ample = mrx.splitlines() print(ample) Make a list where each line is a list element from a string:
  • 76. 76/89 Example: 1 2 3 4 5 6 7 8 9 10 mrx = "**nprogramming language python has the splitlines() method.tIn python it's a built-in methodn**" ample = mrx.splitlines() print(ample) Maintain the line breaks when dividing the string: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "programming language python has the splitlines() method.nIn python it's a built- in method" ample = mrx.splitlines(True) print(ample) Python Strings Method startswith()
  • 77. 77/89 If the string begins with the given value, the startswith() method provides True, else False. Syntax string.startswith(value, start, end) Parameter Values Parameter Description value It is necessary. To find out if the string begins with this value start A choice. An integer specifying where the search should begin end A choice. The location at which the search should terminate is an integer. Make sure the string begins with “Greetings”: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Greetings, we are learning about the Python startswith() method" ample = mrx.startswith("Greetings") print(ample) Verify that the string begins with “Greetings”: Example: 1 2 3
  • 78. 78/89 4 5 6 7 8 9 10 11 mrx = "Greetings, we are learning about the Python startswith() method" mrx = mrx.lower() ample = mrx.startswith("Greetings") print(ample) Make sure position 18 to 40 begins with “lear”: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Greetings, we are learning about the Python startswith() method" ample = mrx.startswith("lear",18, 40) print(ample) Python Strings Method strip() The strip() method eliminates preceding (spaces at the beginning) and following (spaces at the last) characters (by default, a space is the leading character). Syntax string.strip(characters) Parameter Values
  • 79. 79/89 Parameter Description characters A choice. Characters to eliminate as preceding/following characters. Take out the spaces at the start and at the tail of the string: Example: 1 2 3 4 5 6 7 8 9 10 mrx = " BEST " ample = mrx.strip() print("Python is the", ample,"Programming Language") Pass the value “*” in the rstrip() method: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "**********BEST**********" ample = mrx.strip("*") print("Python is the", ample,"Programming Language") Take out the preceding and following characters:
  • 80. 80/89 Example: 1 2 3 4 5 6 7 8 9 10 mrx = ">" ample = mrx.strip("") print("Python is the", ample,"Programming Language") Python Strings Method swapcase() By calling the swapcase() method, you can get a string that includes all uppercase letters transformed into lowercase letters, and the reverse. Syntax string.swapcase() Parameters not required – Change the small case letters to capital case and the capital case letters to small case: Example: 1 2 3 4 5 6 7 8 9
  • 81. 81/89 10 mrx = "hApPy bIRth dAy harry" ample = mrx.swapcase() print(ample) Apply the non-alphabetic characters: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "!!h@pPy bIRth d@y h@rry!!" ample = mrx.swapcase() print(ample) Python Strings Method title() The title() method generates a string with the first character in every word uppercase. It’s like a header or a title. Words including numbers or symbols will be transformed into uppercase after the first letter. Syntax string.title() Parameters are not required – Make sure every word begins with an uppercase letter: Example: 1
  • 82. 82/89 2 3 4 5 6 7 8 9 10 mrx = "guido van rossum is the founder of Python language" ample = mrx.title() print(ample) Verify that every word begins with an uppercase letter in the following example: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "GUIDO VAN ROSSUM is the founder of PYTHON language" ample = mrx.title() print(ample) Ensure that the initial letter of each word is uppercase: Example: 1 2 3 4 5 6
  • 83. 83/89 7 8 9 10 mrx = "**Python is the 1st easy to learn language in the world**" ample = mrx.title() print(ample) In the following example, check that the initial letter after a non-alphabet letter is changed to uppercase: Example: 1 Python Strings Method translate() Translate() generates a string having some chosen characters substituted with the character stored in a dictionary or mapping table. To make a mapping table, call the maketrans() method. In the absence of a dictionary/table, a character will not be substituted. In place of characters, you must utilize ASCII codes when referring to a dictionary. Syntax string.translate(table) Parameter Values Parameter Description table This is essential. Explains how to substitute a value in a dictionary or mapping table. If there is a “K” letter, substitute it with a “J” letter: Example:
  • 84. 84/89 1 2 3 4 5 6 7 8 9 10 11 #Utilize a dictionary with ASCII codes to substitute 75 (K) with 74 (J): mrx_dict = {75: 74} ample = "Greetings Kane.." print(ample.translate(mrx_dict)) Substitute “K” with “J” through a mapping table: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "Greetings Kane.." ample_table = mrx.maketrans("K", "J") print(mrx.translate(ample_table)) To substitute multiple characters, utilize a mapping table: Example: 1 2 3
  • 85. 85/89 4 5 6 7 8 9 10 11 12 13 mrx = "Eva" ample1 = "aEv" ample2 = "yAm" mrx_table = mrx.maketrans(ample1, ample2) print(mrx.translate(mrx_table)) You can delete characters from the string through the third parameter in the mapping table: Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 mrx = "Bonjour Eva!!" ample1 = "Eva" ample2 = "Lia" ample3 = "Bonjour" mrx_table = mrx.maketrans(ample1, ample2, ample3) print(mrx.translate(mrx_table)) Utilizing a dictionary rather than a mapping table, here is the same example as above:
  • 86. 86/89 Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "Bonjour Eva!!" ample_dict = {69: 76, 118: 105, 97: 97, 66: None, 111: None, 110: None, 106: None, 117: None, 114: None} print(mrx.translate(ample_dict)) Python Strings Method upper() upper() method generates a string that contains all letters in capital case. Numbers and symbols are not taken into account. Syntax string.upper() There are no parameters – Make the string larger case: Example: 1 2 3 4 5 6 7 8
  • 87. 87/89 9 10 mrx = "Welcome to PYTHON Strings upper() Method." ample = mrx.upper() print(ample) Apply the digits at the beginning of the string then convert the string to capital case: Example: 1 2 3 4 5 6 7 8 9 10 mrx = "3.11.1 is the latest version of python!" ample = mrx.upper() print(ample) Python Strings Method zfill() The zfill() method inserts zeros (0) at the start of a string until it reaches the given length. There is no filling if len is smaller than the length of the string. Syntax string.zfill(len) Parameter Values Parameter Description len This is necessary. The length of the string should be represented by a number. To make the string 6 characters wide, fill it with zeros:
  • 88. 88/89 Example: 1 2 3 4 5 6 7 8 9 10 mrx = "88" ample = mrx.zfill(6) print(ample) Implement the zfill() method to string then utilize upper() method: Example: 1 2 3 4 5 6 7 8 9 10 11 mrx = "mrexamples" ample = mrx.zfill(15) ample = ample.upper() print(ample) To make the strings various characters wide, fill them with zeros: Example:
  • 89. 89/89 1 2 3 4 5 6 7 8 9 10 11 12 mrx1 = "Greetings" mrx2 = "Python zfill() method" mrx3 = "20499" print(mrx1.zfill(15)) print(mrx2.zfill(9)) print(mrx3.zfill(7)) Having learned about Python strings methods and how they work, you are now prepared to use them.