Python Strings
What are strings?
In python, anything that you enclose between single or double quotation
marks is considered a string. A string is essentially a sequence or array of
textual data.
Strings are used when working with Unicode characters.
Example:
name = "Samuel"
print("Hello,
" +
name)
Output:
Hello, Samuel
Note: It does not
matter whether you enclose your strings in single or double quotes, the output
remains the same.
Sometimes, the user might need to put quotation marks in between the
strings. Example, consider the sentence: He said, “I want to eat an apple”.
How will you print this statement in python?
Wrong way ❌
print("He
said, "I want to eat an apple".")
Output:
print("He said, "I want to
eat an apple".")
^
SyntaxError: invalid syntax
Right way ✔️
print('He
said, "I want to eat an apple".')
#OR
print("He
said, \"I want to eat an apple\".")
Output:
He said, "I want to eat an
apple".
He said, "I want to eat an
apple".
What if you want to
write multiline strings?
Sometimes the programmer might want to include a note, or a set of
instructions, or just might want to explain a piece of code. Although this
might be done using multiline comments, the programmer may want to display this
in the execution of programmer. This is done using multiline strings.
Example:
receipe = """
1. Heat the pan and add oil
2. Crack the egg
3. Add salt in egg and mix well
4. Pour the mixture in pan
5. Fry on medium heat
"""
print(receipe)
note = '''
This is a multiline string
It is used to display multiline message
in the program
'''
print(note)
Output:
1. Heat the pan and add oil
2. Crack the egg
3. Add salt in egg and mix well
4. Pour the mixture in pan
5. Fry on medium heat
This is a multiline string
It is used to display multiline message
in the program
Operation on
Strings
Length of a String:
We can find the length of a string using len() function.
Example:
fruit = "Mango"
len1 = len(fruit)
print("Mango
is a",
len1, "letter
word.")
Output:
Mango is a 5 letter word.
String as an Array:
A string is essentially a sequence of characters also called an array.
Thus we can access the elements of this array.
Example:
pie = "ApplePie"
print(pie[:5])
print(pie[6]) #returns character at specified index
Output:
Apple
i
Note: This method of
specifying the start and end index to specify a part of a string is called
slicing.
Example:
pie = "ApplePie"
print(pie[:5]) #Slicing from Start
print(pie[5:]) #Slicing till End
print(pie[2:6]) #Slicing in between
print(pie[-8:]) #Slicing using negative index
Output:
Apple
Pie
pleP
ApplePie
Loop through a
String:
Strings are arrays and arrays are iterable. Thus we can loop through
strings.
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
A
B
C
D
E
String Methods
Python provides a set of built-in
methods that we can use to alter and modify the strings.
upper() : The upper() method
converts a string to upper case.
Example:
str1
="AbcDEfghIJ"
print(str1
.upper
())
Output:
ABCDEFGHIJ
lower()
: The lower() method converts a string to upper case.
Example:
str1
="AbcDEfghIJ"
print(str1
.lower
())
Output:
abcdefghij
strip()
: The strip() method removes any white spaces before and after the string.
Example:
str2
=" Silver Spoon "
print(str2
.strip
)
Output:
Silver Spoon
rstrip()
: the rstrip() removes any trailing characters.
Example:
str3
="Hello !!!"
print(str3
.rstrip
("!"))
Output:
Hello
replace()
: the replace() method replaces a string with another string.
Example:
str2
="Silver Spoon"
print(str2
.replace
("Sp","M"))
Output:
Silver Moon
split()
: The split() method splits the give string at the specified instance and
returns the separated strings as list items.
Example:
str2
="Silver Spoon"
print(str2
.split
(" "))#Splits the string at the whitespace " ".
Output:
['Silver', 'Spoon']
There are various other string
methods that we can use to modify our strings.
capitalize()
: The capitalize() method turns only the first character of the string to uppercase
and the rest other characters of the string are turned to lowercase. The string
has no effect if the first character is already uppercase.
Example:
str1
="hello"
capStr1
=str1
.capitalize
()
print(capStr1
)
str2
="hello WorlD"
capStr2
=str2
.capitalize
()
print(capStr2
)
Output:
Hello
Hello world
center()
: The center() method aligns the string to the center as per the parameters
given by the user.
Example:
str1
="Welcome to the Console!!!"
print(str1
.center
(50))
Output:
Welcome to the Console!!!
We can also provide padding
character. It will fill the rest of the fill characters provided by the user.
Example:
str1
="Welcome to the Console!!!"
print(str1
.center
(50,"."))
Output:
............Welcome to the Console!!!.............
count()
: The count() method returns the number of times the given value has occurred
within the given string.
Example:
str2
="Abracadabra"
countStr
=str2
.count
("a")
print(countStr
)
Output:
4
endswith()
: The endswith() method checks if the string ends with a given value. If yes
then return True, else return False.
Example 1:
str1
="Welcome to the Console !!!"
print(str1
.endswith
("!!!"))
Output:
True
Example 2:
str1
="Welcome to the Console !!!"
print(str1
.endswith
("Console"))
Output:
False
We can even also check for a
value in-between the string by providing start and end index positions.
Example:
str1
="Welcome to the Console !!!"
print(str1
.endswith
("to",4,
10))
Output:
True
find()
: The find() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the string
then return -1.
Example:
str1
="He's name is Dan. He is an honest man."
print(str1
.find
("is"))
Output:
10
As we can see, this method is
somewhat similar to the index() method. The major difference being that index()
raises an exception if value is absent whereas find() does not.
Example:
str1
="He's name is Dan. He is an honest man."
print(str1
.find
("Daniel"))
Output:
-1
index()
: The index() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the string
then raise an exception.
Example:
str1
="He's name is Dan. Dan is an honest man."
print(str1
.index
("Dan"))
Output:
13
As we can see, this method is
somewhat similar to the find() method. The major difference being that index()
raises an exception if value is absent whereas find() does not.
Example:
str1
="He's name is Dan. Dan is an honest man."
print(str1
.index
("Daniel"))
Output:
ValueError: substring not found
isalnum()
: The isalnum() method returns True only if the entire string only consists of
A-Z, a-z, 0-9. If any other characters or punctuations are present, then it
returns False.
Example 1:
str1
="WelcomeToTheConsole"
print(str1
.isalnum
())
Output:
True
Example 2:
str1
="Welcome To The Console"
print(str1
.isalnum
())
str2
="Hurray!!!"
print(str2
.isalnum
())
Output:
False
False
isalpha()
: The isalnum() method returns True only if the entire string only consists of
A-Z, a-z. If any other characters or punctuations or numbers(0-9) are present,
then it returns False.
Example 1:
str1
="Welcome"
print(str1
.isalpha
())
Output:
True
Example 2:
tr1
="I'm 18 years old"
print(str1
.isalpha
())
str2
="Hurray!!!"
print(str2
.isalnum
())
Output:
False
False
islower()
: The islower() method returns True if all the characters in the string are
lower case, else it returns False.
Example 1:
str1
="hello world"
print(str1
.islower
())
Output:
True
Example 2:
str1
="welcome Mike"
print(str1
.islower
())
str2
="Hurray!!!"
print(str2
.islower
())
Output:
False
False
isprintable()
: The isprintable() method returns True if all the values within the given
string are printable, if not, then return False.
Example 1:
str1
="We wish you a Merry Christmas"
print(str1
.isprintable
())
Output:
True
Example 2:
str2
="Hello, \t\t.Mike"
print(str2
.isprintable
())
Output:
False
isspace()
: The isspace() method returns True only and only if the string contains white
spaces, else returns False.
Example 1:
str1
=" "
#using Spacebar
print(str1
.isspace
())
str2
=" "
#using Tab
print(str2
.isspace
())
Output:
True
True
Example 2:
str1
="Hello World"
print(str1
.isspace
())
Output:
False
istitle()
: The istitile() returns True only if the first letter of each word of the
string is capitalized, else it returns False.
Example 1:
str1
="World Health Organization"
print(str1
.istitle
())
Output:
True
Example 2:
str2
="To kill a Mocking bird"
print(str2
.istitle
())
Output:
False
isupper()
: The isupper() method returns True if all the characters in the string are
upper case, else it returns False.
Example 1:
str1
="WORLD HEALTH ORGANIZATION"
print(str1
.isupper
())
Output:
True
Example 2:
str2
="To kill a Mocking bird"
print(str2
.isupper
())
Output:
False
replace()
: The replace() method can be used to replace a part of the original string
with another string.
Example:
str1
="Python is a Compiled Language."
print(str1
.replace
("Compiled","Interpreted"))
Output:
Python is a Interpreted Language.
startswith()
: The endswith() method checks if the string starts with a given value. If yes
then return True, else return False.
Example 1:
str1
="Python is a Interpreted Language"
print(str1
.startswith
("Python"))
Output:
True
Example 2:
str1
="Python is a Interpreted Language"
print(str1
.startswith
("a"))
Output:
False
We can even also check for a
value in-between the string by providing start and end index positions.
Example:
str1
="Python is a Interpreted Language"
print(str1
.startswith
("Inter",12,
20))
Output:
True
swapcase()
: The swapcase() method changes the character casing of the string. Upper case
are converted to lower case and lower case to upper case.
Example:
str1
="Python is a Interpreted Language"
print(str1
.swapcase
())
Output:
pYTHON IS A iNTERPRETED lANGUAGE
title()
: The title() method capitalizes each letter of the word within the string.
Example:
str1
="He's name is Dan. Dan is an honest man."
print(str1
.title
())
Output:
He'S Name Is Dan. Dan Is An Honest Man.
0 Comments