Strings in Python
Strings in Python
Strings in Python
• A string is a sequence of characters.
• A character is simply a symbol.
• Computers do not deal with characters, they deal with numbers (binary).
• This conversion of character to a number is called encoding, and the
reverse process is decoding.
• ASCII and Unicode are some of the popular encodings used.
• In Python, a string is a sequence of Unicode characters.
• Unicode was introduced to include every character in all languages and
bring uniformity in encoding.
Creating a String
• my_string = 'Hello'
• print(my_string)
• my_string = "Hello"
• print(my_string)
• my_string = '''Hello'''
• print(my_string)
• # triple quotes string can extend multiple lines
my_string = """Hello, welcome to the
world of Python"""
print(my_string)
Output
• Output
• Hello
• Hello
• Hello
• Hello, welcome to
the world of Python
Strings indexing and splitting
str = "RAJALAKSHMI"
# Start 0th index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 9th index
print(str[4:9])
Output
RAJALAKSHMI
AJAL
JA
RAJ
LAKSH
Output
H
E
L
L
O
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-2-72aac026d8d5> in <module>
6 print(str[4])
7 # It returns the IndexError because 6th index doesn't exist
----> 8 print(str[6])
str = "RAJALAKSHMI"
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Reassigning Strings
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
print the actual meaning of escape characters such as "C://python". To define any string
as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.
Example
str = "Hello"
str1 = " world"
print(str*3)
print(str+str1)
print(str[4])
print(str[2:4])
print('w' in str)
print('wo' not in str1)
print(r'C://python37')
print("The string str : %s"%(str))
Output
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Escape Sequences
print("They said, \"What's going on?\"")
Output
They said, "What's going on?"
List of escape sequences are as
below
Sr. Escape Sequence Description Example
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output
Devansh and Abhishek both are the best friend
Rohit and Virat best players
James,Peter,Ricky
Python String functions
Method Description
center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.
str="Rajalakshmi"
print(str.casefold())
Output
rajalakshmi
str='RAJALAKSHMI'
str.center(30,'#')
output
'#########RAJALAKSHMI##########'
Count Method
str = "rajalakshmi"
str2 = str.count('a')
# Displaying result
print("occurences:", str2)
Output
Occurences:3
Count() Method 2
str = "abbccadeedaddaabbcca"
oc = str.count('a', 3)
# Displaying result
print("occurences:", oc
output
occurences: 5
Count() Method 3
str = "ab bc ca de ed ad da ab bc ca"
oc = str.count('a', 3, 8)
# Displaying result
print("occurences:", oc)
output
occurences: 5
Python String endswith() Method
Python endswith() method returns true of the string ends with the
specified substring, otherwise returns false.
Signature
endswith(suffix[, start[, end]])
Parameters
suffix : a substring
start : start index of a range
end : last index of the range
Start and end both parameters are optional.
• Return Type
• It returns a boolean value either True or False.
Example 1
Python find() method finds substring in the whole string and returns index of
the first match. It returns -1 if substring does not match.
Signature
find(sub[, start[, end]])
Parameters
sub : substring
start : start index a range
end : last index of the range
Return Type
If found it returns index of the substring, otherwise -1.
Example 1
Python index() method is same as the find() method except it returns error on failure. This
method returns index of first occurred substring and an error if there is no match found.
Signature
index(sub[, start[, end]])
Parameters
sub : substring
start : start index a range
end : last index of the range
Return Type
If found it returns an index of the substring, otherwise an error ValueError.
Example 1
str = "Welcome to the python."
# Calling function
str2 = str.index("to")
# Displaying result
print(str2)
output
8
str = "Welcome to the python."
# Calling function
str2 = str.index("at")
# Displaying result
print(str2)
output
Traceback (most recent call last):
File "main.py", line 7, in <module>
str2 = str.index("at")
ValueError: substring not found
str = "Welcome to the python."
str2 = str.index('o',0,6)
# Displaying result
print("o is present at :",str2,"index")
Output
o is present at : 4 index
Python String isalnum() Method
Return
It returns either True or False.
str = 'Welcome'
# Calling function
str2 = str.isalnum()
# Displaying result
print(str2)
output
True
Python String isalpha() Method
Python isalpha() method returns true if all characters in the string are
alphabetic. It returns False if the characters are not alphabetic. It
returns either True or False.
Signature
isalpha()
Parameters
No parameter is required.
Return
It returns either True or False.
str = 'Welcome'
# Calling function
str2 = str.isalpha()
# Displaying result
print(str2)
Output
True
Python String isdecimal()
Method
Python isdecimal() method checks whether all the characters in the
string are decimal or not. Decimal characters are those have base 10.
This method returns boolean either true or false.
Signature
isdecimal()
Parameters
No parameter is required.
Return
It returns either True or False.
Example 1
str = "123" # True
str3 = "2.50" # False
# Calling function
str2 = str.isdecimal()
str4 = str3.isdecimal()
# Displaying result
print(str2)
print(str4)
Output
True
False
Python String isdigit() Method
Python isdigit() method returns True if all the characters in the string are digits.
It returns False if no character is digit in the string.
Signature
isdigit()
Parameters
No parameter is required.
Return
It returns either True or False.
str = '123' # True
str3 = '2.50' # False
# Calling function
str2 = str.isdigit()
str4 = str3.isdigit()
# Displaying result
print(str2)
print(str4)
Output
True
False
Python String isidentifier() Method
•Python isidentifier() method is used to check whether a string is a valid identifier or not.
• It returns True if the string is a valid identifier otherwise returns False.
• Python language has own identifier definition which is used by this method.
Signature
isidentifier()
Parameters
No parameter is required.
Return
It returns either True or False.
str = "abcdef"
str2 = "20xyz"
str3 = "$abra"
# Calling function
str4 = str.isidentifier()
str5 = str2.isidentifier()
str6 = str3.isidentifier()
# Displaying result
print(str4)
print(str5)
print(str6)
Output
True
False
False
Python String islower() Method
The islower() method returns True if all the characters are in lower
case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet
characters.
Syntax
string.islower()
str = 'python'
str3 ='PYTHON'
str2 = str.islower()
str4 = str3.isupper()
print(str2)
print(str4)
str2 = str3.islower()
str4 = str.isupper()
# Displaying result
print(str2)
print(str4)
Output
True
True
False
False