Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Strings in Python

STRINGS IN PYTHON

Uploaded by

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

Strings in Python

STRINGS IN PYTHON

Uploaded by

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

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

• Indexing of the Python strings starts from 0.


• For example, The string "HELLO" is indexed as given in the below
figure.
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[6])
Example 1

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

IndexError: string index out of range


Example

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

• Updating the content of the strings is as easy as assigning it to a new


string.
• The string object doesn't support item assignment.
• A string can only be replaced with new string since its content cannot
be partially replaced.
• Strings are immutable in Python.
str = "HELLO"
str[0] = "h" print(str)
Output
TypeError Traceback (most recent call last)<ipython-
input-7-8507b020b978> in <module>
1 str ="HELLO“
----> 2str[0]="h"
3print(str)
TypeError: 'str' object does not support item assignment
Deleting the String
• As we know that strings are immutable.
• We cannot delete or remove the characters from the string.
• But we can delete the entire string using the del keyword.
str = "PYTHON“
del str[1]
Output:
TypeError: 'str' object doesn't support item
string1 = "PYTHON“
Print(string1)
del string1
print(string1)
Output:
PYTHON
Traceback (most recent call last):
File "<string>", line 7, in <module>
NameError: name 'string1' is not defined
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
in It is known as membership operator. It returns if a particular sub-string is present in the
specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.

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

1. \newline It ignores the new print("Python1 \


line. Python2 \
Python3")
Output:
Python1 Python2 Python3
2. \\ Backslash print("\\")
Output:
\
3. \' Single Quotes print('\'')
Output:
'
4. \\'' Double Quotes print("\"")
Output:
"
The format() method

• The format() method is the most flexible and useful method in


formatting strings.
• The curly braces {} are used as the placeholder in the string and
replaced by the format() method argument.
# Using Curly braces
print("{} and {} both are the bestfriend“.format("Devansh","Abhishek"))

#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

capitalize() It capitalizes the first character of the String. This function is


deprecated in python3

casefold() It returns a version of s suitable for case-less comparisons.

center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.

count(string,begin,end) It counts the number of occurrences of a substring in a String


between begin and end index.
Output
str='rajalakshmi'
print(str.capitalize())
Output
Rajalakshmi

str="Rajalakshmi"
print(str.casefold())

Output
rajalakshmi
str='RAJALAKSHMI'
str.center(30,'#')

output
'#########RAJALAKSHMI##########'
Count Method

Syntax of String count


The syntax of count() method is:

string.count(substring, start=..., end=...)


string.count(substring, start=..., end=...)
count() method only requires a single parameter for execution.
substring - string whose count is to be found.
start (Optional) - starting index within the string where search starts.
end (Optional) - ending index within the string where search ends.
Note: Index in Python starts from 0, not 1.
count() Return Value
count() method returns the number of occurrences of the substring in
the given string.
Count() Method 1

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

str = "Hello this is python class"


isends = str.endswith('class')
# Displaying result
print(isends)
Output
True
str = "Hello this is python class."
isends = str.endswith('o',0,5)
# Displaying result
print(isends)
Output
True
Python String find() Method

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

str = 'Welcome to the python class'


# Calling function
str2 = str.find('the')
# Displaying result
print(str2)
output
11
Example 2
str = 'Welcome to the python class'
# Calling function
str2 = str.find('is')
# Displaying result
print(str2)
output
-1
Example 3
str = 'Welcome to the python class'
# Calling function
str2 = str.find('t')
# Displaying result
print(str2)
str3 = str.find('t',25)
# Displaying result
print(str3)
output
8
-1
Python String index() Method

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

• Python isalnum() method checks whether the all characters of the


string is alphanumeric or not.
• A character which is either a letter or a number is known as
alphanumeric.
• It does not allow special chars even spaces.
Signature
isalnum()
Parameters
No parameter is required.

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

You might also like