SlideShare a Scribd company logo
Strings
Team Emertxe
Strings And Characters
Strings And Characters
Creating Strings
Example-1 s = 'Welcome to Python'
Example-2 s = "Welcome to Python"
Example-3 s = """
Welcome to Python
"""
Example-4 s = '''
Welcome to Python
'''
Example-5 s = "Welcome to 'Core' Python"
Example-6 s = 'Welcome to "Core" Python'
Example-7 s = "Welcome totCorenPython"
Example-8 s = r"Welcome totCorenPython"
Strings And Characters
Length of a String
len() Is used to find the length of the string
Example str = "Core Python"
n = len(str)
print("Len: ", n)
Strings And Characters
Indexing the Strings
str = "Core Python"
#Method-1: Access each character using
while loop
n = len(str)
i = 0
while i < n:
print(str[i], end=' ')
i += 1
#Method-2: Using for loop
for i in str:
print(i, end=' ')
#Method-3: Using slicing operator
for i in str[::]:
print(i, end='')
print()
#Method-4: Using slicing operator
#Take sthe step size as -1
for i in str[: : -1]:
print(i, end='')

Both positive and Negative indexing is possible in Python
Strings And Characters
Slicing the Strings
str = "Core Python"
1 str[: :]
Prints all
2 str[0: 9: 1]
Access the string from 0th to 8th element
3 str[0: 9: 2]
Access the string in the step size of 2
4 str[2: 3: 1]
Access the string from 2nd to 3rd Character
5 str[: : 2] Access the entire string in the step size of 2
6 str[: 4: ] Access the string from 0th to 3rd location in steps of 1
7 str[-4: -1: ] Access from str[-4] to str[-2] from left to right
8 str[-6: :] Access from -6 till the end of the string
9 str[-1: -4: -1] When stepsize is negative, then the items are counted from right to
left
10 str[-1: : -1] Retrieve items from str[-1] till the first element from right to left
Strings And Characters
Repeating the Strings

The repetition operator * is used for repeating the strings
Example-1 str = "Core Python"
print(str * 2)
Example-2
print(str[5: 7] * 2)
Strings And Characters
Concatenation of Strings

+ is used as a concatenation operator
Example-1 s1 = "Core"
s2 = "Python"
s3 = s1 + s2
Strings And Characters
Membership Operator

We can check, if a string or a character is a member of another string or not using
'in' or 'not in' operator

'in' or 'not in' makes case sensitive comaprisons
Example-1 str = input("Enter the first string: ")
sub = input("Enter the second string: ")
if sub in str:
print(sub+" is found in main string")
else:
print(sub+" is not found in main string")
Strings And Characters
Removing Spaces
str = " Ram Ravi "
lstrip() #Removes spaces from the left side
print(str.lstrip())
rstrip() #Removes spaces from the right side
print(str.rstrip())
strip() #Removes spaces from the both sides
print(str.strip())
Strings And Characters
Finding the Sub-Strings

Methods useful for finding the strings in the main string

- find()

- rfind()

- index()

- rindex()

find(), index() will search for the sub-string from the begining

rfind(), rindex() will search for the sub-string from the end

find(): Returns -1, if sub-string is not found

index(): Returns 'ValueError' if the sub-string is not found
Strings And Characters
Finding the Sub-Strings
Syntax mainstring.find(substring, beg, end)
Example str = input("Enter the main string:")
sub = input("Enter the sub string:")
#Search for the sub-string
n = str.find(sub, 0, len(str))
if n == -1:
print("Sub string not found")
else:
print("Sub string found @: ", n + 1)
Strings And Characters
Finding the Sub-Strings
Syntax mainstring.index(substring, beg, end)
Example str = input("Enter the main string:")
sub = input("Enter the sub string:")
#Search for the sub-string
try:
#Search for the sub-string
n = str.index(sub, 0, len(str))
except ValueError:
print("Sub string not found")
else:
print("Sub string found @: ", n + 1)
Strings And Characters
Finding the Sub-Strings: Exercise
1 To display all positions of a sub-string in a given main string
Strings And Characters
Counting Sub-Strings in a String
count() To count the number of occurrences of a sub-string in a main string
Syntax stringname.count(substring, beg, end)
Example-1 str = “New Delhi”
n = str.count(‘Delhi’)
Example-2 str = “New Delhi”
n = str.count(‘e’, 0, 3)
Example-3 str = “New Delhi”
n = str.count(‘e’, 0, len(str))
Strings And Characters
Strings are Immutable

Immutable object is an object whose content cannot be changed
Immutable Numbers, Strings, Tuples
Mutable Lists, Sets, Dictionaries
Reasons: Why strings are made immutable in Python
Performance Takes less time to allocate the memory for the Immutable objects, since
their memory size is fixed
Security Any attempt to modify the string will lead to the creation of new object in
memory and hence ID changes which can be tracked easily
Strings And Characters
Strings are Immutable

Immutable object is an object whose content cannot be changed

Example:

s1 = “one”

s2 = “two”

S2 = s1
one two
S1 S2
one two
S1 S2
Strings And Characters
Replacing String with another String
replace() To replace the sub-string with another sub-string
Syntax stringname.replace(old, new)
Example str = "Ram is good boy"
str1 = str.replace("good", "handsome")
print(str1)
Strings And Characters
Splitting And Joining Strings
join() - Groups into one sring
Syntax separator.join(str)
- separator: Represents the character to be used between two strings
- str: Represents tuple or list of strings
Example str = ("one", "two", "three")
str1 = "-".join(str)
split() - Used to brake the strings
- Pieces are returned as a list
Syntax stringname.split(‘character’)
Example str = "one,two,three"
lst = str.split(',')
Strings And Characters
Changing the Case of the Strings
Methods upper()
lower()
swapcase()
title()
str = "Python is the future"
upper() print(str.upper()) PYTHON IS THE FUTURE
lower() print(str.lower()) python is the future
swapcase() print(str.swapcase()) pYTHON IS THE FUTURE
title() print(str.title()) Python Is The Future
Strings And Characters
Check: Starting & Ending of Strings
Methods startswith()
endswith()
str = "This is a Python"
startswith() print(str.startswith("This")) True
endswith() print(str.endswith("This")) False
Strings And Characters
String Testing Methods
isalnum() Returns True, if all characters in the string are alphanumeric(A – Z, a – z, 0
– 9) and there is atleast one character
isalpha() Returns True, if the string has atleast one character and all characters are
alphabets(A - Z, a – z)
isdigit() Returns True if the string contains only numeric digits(0-9) and False
otherwise
islower() Returns True if the string contains at least one letter and all characters are
in lower case; otherwise it returns False
isupper() Returns True if the string contains at least one letter and all characters are
in upper case; otherwise it returns False
istitle() Returns True if each word of the string starts with a capital letter and there
at least one character in the string; otherwise it returns False
isspace() Returns True if the string contains only spaces; otherwise, it returns False
Strings And Characters
Formatting the strings
format() Presenting the string in the clearly understandable manner
Syntax
"format string with replacement fields". format(values)
id = 10
name = "Ram"
sal = 19000.45
print("{}, {}, {}". format(id, name, sal))
print("{}-{}-{}". format(id, name, sal))
print("ID: {0}tName: {1}tSal: {2}n". format(id, name, sal))
print("ID: {2}tName: {0}tSal: {1}n". format(id, name, sal))
print("ID: {two}tName: {zero}tSal: {one}n". format(zero=id, one=name, two=sal))
print("ID: {:d}tName: {:s}tSal: {:10.2f}n". format(id, name, sal))
Strings And Characters
Formatting the strings
format() Presenting the string in the clearly understandable manner
Syntax
"format string with replacement fields". format(values)
n = 5000
print("{:*>15d}". format(num))
print("{:*^15d}". format(num))
Strings And Characters
Exercise
1. To know the type of character entered by the user
2. To sort the strings in alphabetical order
3. To search for the position for a string in agiven group of strings
4. To find the number of words in a given strings
5. To insert the sub-string into a main string in a particular position
THANK YOU

More Related Content

What's hot (20)

PDF
Python tuple
Mohammed Sikander
 
PDF
Datatypes in python
eShikshak
 
PDF
Introduction to Python
Mohammed Sikander
 
PPTX
Looping Statements and Control Statements in Python
PriyankaC44
 
PPTX
Strings in C language
P M Patil
 
PPTX
Python Functions
Mohammed Sikander
 
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PDF
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
PPTX
Data types in python
RaginiJain21
 
PDF
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
PPTX
Arrays in java
bhavesh prakash
 
PPTX
JAVA AWT
shanmuga rajan
 
PPT
Looping statements in Java
Jin Castor
 
PDF
Python list
Mohammed Sikander
 
PDF
Arrays in python
moazamali28
 
PPTX
Functions in c language
tanmaymodi4
 
PDF
Python exception handling
Mohammed Sikander
 
PPTX
Constructor in java
Pavith Gunasekara
 
PDF
Python functions
Prof. Dr. K. Adisesha
 
Python tuple
Mohammed Sikander
 
Datatypes in python
eShikshak
 
Introduction to Python
Mohammed Sikander
 
Looping Statements and Control Statements in Python
PriyankaC44
 
Strings in C language
P M Patil
 
Python Functions
Mohammed Sikander
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Data types in python
RaginiJain21
 
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Arrays in java
bhavesh prakash
 
JAVA AWT
shanmuga rajan
 
Looping statements in Java
Jin Castor
 
Python list
Mohammed Sikander
 
Arrays in python
moazamali28
 
Functions in c language
tanmaymodi4
 
Python exception handling
Mohammed Sikander
 
Constructor in java
Pavith Gunasekara
 
Python functions
Prof. Dr. K. Adisesha
 

Similar to Python programming : Strings (20)

PDF
Strings brief introduction in python.pdf
TODAYIREAD1
 
PPTX
Python Strings and its Featues Explained in Detail .pptx
parmg0960
 
PPTX
trisha comp ppt.pptx
Tapaswini14
 
PDF
Python data handling
Prof. Dr. K. Adisesha
 
PPTX
Chapter 11 Strings and methods [Autosaved].pptx
geethar79
 
PPTX
string manipulation in python ppt for grade 11 cbse
KrithikaTM
 
PPTX
Python Strings.pptx
adityakumawat625
 
PPTX
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
PPTX
UNIT 4 python.pptx
TKSanthoshRao
 
PPTX
Engineering string(681) concept ppt.pptx
ChandrashekarReddy98
 
PPTX
chapte_6_String_python_bca_2005_computer
hansibansal
 
PDF
Strings in Python
nitamhaske
 
PPTX
Detailed description of Strings in Python
Keerthiraja11
 
PPTX
Strings.pptx
Yagna15
 
PPT
PPS_Unit 4.ppt
KundanBhatkar
 
PPTX
varthini python .pptx
MJeyavarthini
 
PPTX
stringggg.pptxtujd7ttttttttttttttttttttttttttttttttttt
pawankamal3
 
PPTX
Chapter 14 strings
Praveen M Jigajinni
 
PPTX
Chapter 11 Strings.pptx
afsheenfaiq2
 
PDF
Python strings
Aswini Dharmaraj
 
Strings brief introduction in python.pdf
TODAYIREAD1
 
Python Strings and its Featues Explained in Detail .pptx
parmg0960
 
trisha comp ppt.pptx
Tapaswini14
 
Python data handling
Prof. Dr. K. Adisesha
 
Chapter 11 Strings and methods [Autosaved].pptx
geethar79
 
string manipulation in python ppt for grade 11 cbse
KrithikaTM
 
Python Strings.pptx
adityakumawat625
 
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
UNIT 4 python.pptx
TKSanthoshRao
 
Engineering string(681) concept ppt.pptx
ChandrashekarReddy98
 
chapte_6_String_python_bca_2005_computer
hansibansal
 
Strings in Python
nitamhaske
 
Detailed description of Strings in Python
Keerthiraja11
 
Strings.pptx
Yagna15
 
PPS_Unit 4.ppt
KundanBhatkar
 
varthini python .pptx
MJeyavarthini
 
stringggg.pptxtujd7ttttttttttttttttttttttttttttttttttt
pawankamal3
 
Chapter 14 strings
Praveen M Jigajinni
 
Chapter 11 Strings.pptx
afsheenfaiq2
 
Python strings
Aswini Dharmaraj
 
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Ad

Recently uploaded (20)

PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PPTX
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
PPTX
The birth and death of Stars - earth and life science
rizellemarieastrolo
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
Next level data operations using Power Automate magic
Andries den Haan
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
The birth and death of Stars - earth and life science
rizellemarieastrolo
 
Kubernetes - Architecture & Components.pdf
geethak285
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Next level data operations using Power Automate magic
Andries den Haan
 

Python programming : Strings

  • 3. Strings And Characters Creating Strings Example-1 s = 'Welcome to Python' Example-2 s = "Welcome to Python" Example-3 s = """ Welcome to Python """ Example-4 s = ''' Welcome to Python ''' Example-5 s = "Welcome to 'Core' Python" Example-6 s = 'Welcome to "Core" Python' Example-7 s = "Welcome totCorenPython" Example-8 s = r"Welcome totCorenPython"
  • 4. Strings And Characters Length of a String len() Is used to find the length of the string Example str = "Core Python" n = len(str) print("Len: ", n)
  • 5. Strings And Characters Indexing the Strings str = "Core Python" #Method-1: Access each character using while loop n = len(str) i = 0 while i < n: print(str[i], end=' ') i += 1 #Method-2: Using for loop for i in str: print(i, end=' ') #Method-3: Using slicing operator for i in str[::]: print(i, end='') print() #Method-4: Using slicing operator #Take sthe step size as -1 for i in str[: : -1]: print(i, end='')  Both positive and Negative indexing is possible in Python
  • 6. Strings And Characters Slicing the Strings str = "Core Python" 1 str[: :] Prints all 2 str[0: 9: 1] Access the string from 0th to 8th element 3 str[0: 9: 2] Access the string in the step size of 2 4 str[2: 3: 1] Access the string from 2nd to 3rd Character 5 str[: : 2] Access the entire string in the step size of 2 6 str[: 4: ] Access the string from 0th to 3rd location in steps of 1 7 str[-4: -1: ] Access from str[-4] to str[-2] from left to right 8 str[-6: :] Access from -6 till the end of the string 9 str[-1: -4: -1] When stepsize is negative, then the items are counted from right to left 10 str[-1: : -1] Retrieve items from str[-1] till the first element from right to left
  • 7. Strings And Characters Repeating the Strings  The repetition operator * is used for repeating the strings Example-1 str = "Core Python" print(str * 2) Example-2 print(str[5: 7] * 2)
  • 8. Strings And Characters Concatenation of Strings  + is used as a concatenation operator Example-1 s1 = "Core" s2 = "Python" s3 = s1 + s2
  • 9. Strings And Characters Membership Operator  We can check, if a string or a character is a member of another string or not using 'in' or 'not in' operator  'in' or 'not in' makes case sensitive comaprisons Example-1 str = input("Enter the first string: ") sub = input("Enter the second string: ") if sub in str: print(sub+" is found in main string") else: print(sub+" is not found in main string")
  • 10. Strings And Characters Removing Spaces str = " Ram Ravi " lstrip() #Removes spaces from the left side print(str.lstrip()) rstrip() #Removes spaces from the right side print(str.rstrip()) strip() #Removes spaces from the both sides print(str.strip())
  • 11. Strings And Characters Finding the Sub-Strings  Methods useful for finding the strings in the main string  - find()  - rfind()  - index()  - rindex()  find(), index() will search for the sub-string from the begining  rfind(), rindex() will search for the sub-string from the end  find(): Returns -1, if sub-string is not found  index(): Returns 'ValueError' if the sub-string is not found
  • 12. Strings And Characters Finding the Sub-Strings Syntax mainstring.find(substring, beg, end) Example str = input("Enter the main string:") sub = input("Enter the sub string:") #Search for the sub-string n = str.find(sub, 0, len(str)) if n == -1: print("Sub string not found") else: print("Sub string found @: ", n + 1)
  • 13. Strings And Characters Finding the Sub-Strings Syntax mainstring.index(substring, beg, end) Example str = input("Enter the main string:") sub = input("Enter the sub string:") #Search for the sub-string try: #Search for the sub-string n = str.index(sub, 0, len(str)) except ValueError: print("Sub string not found") else: print("Sub string found @: ", n + 1)
  • 14. Strings And Characters Finding the Sub-Strings: Exercise 1 To display all positions of a sub-string in a given main string
  • 15. Strings And Characters Counting Sub-Strings in a String count() To count the number of occurrences of a sub-string in a main string Syntax stringname.count(substring, beg, end) Example-1 str = “New Delhi” n = str.count(‘Delhi’) Example-2 str = “New Delhi” n = str.count(‘e’, 0, 3) Example-3 str = “New Delhi” n = str.count(‘e’, 0, len(str))
  • 16. Strings And Characters Strings are Immutable  Immutable object is an object whose content cannot be changed Immutable Numbers, Strings, Tuples Mutable Lists, Sets, Dictionaries Reasons: Why strings are made immutable in Python Performance Takes less time to allocate the memory for the Immutable objects, since their memory size is fixed Security Any attempt to modify the string will lead to the creation of new object in memory and hence ID changes which can be tracked easily
  • 17. Strings And Characters Strings are Immutable  Immutable object is an object whose content cannot be changed  Example:  s1 = “one”  s2 = “two”  S2 = s1 one two S1 S2 one two S1 S2
  • 18. Strings And Characters Replacing String with another String replace() To replace the sub-string with another sub-string Syntax stringname.replace(old, new) Example str = "Ram is good boy" str1 = str.replace("good", "handsome") print(str1)
  • 19. Strings And Characters Splitting And Joining Strings join() - Groups into one sring Syntax separator.join(str) - separator: Represents the character to be used between two strings - str: Represents tuple or list of strings Example str = ("one", "two", "three") str1 = "-".join(str) split() - Used to brake the strings - Pieces are returned as a list Syntax stringname.split(‘character’) Example str = "one,two,three" lst = str.split(',')
  • 20. Strings And Characters Changing the Case of the Strings Methods upper() lower() swapcase() title() str = "Python is the future" upper() print(str.upper()) PYTHON IS THE FUTURE lower() print(str.lower()) python is the future swapcase() print(str.swapcase()) pYTHON IS THE FUTURE title() print(str.title()) Python Is The Future
  • 21. Strings And Characters Check: Starting & Ending of Strings Methods startswith() endswith() str = "This is a Python" startswith() print(str.startswith("This")) True endswith() print(str.endswith("This")) False
  • 22. Strings And Characters String Testing Methods isalnum() Returns True, if all characters in the string are alphanumeric(A – Z, a – z, 0 – 9) and there is atleast one character isalpha() Returns True, if the string has atleast one character and all characters are alphabets(A - Z, a – z) isdigit() Returns True if the string contains only numeric digits(0-9) and False otherwise islower() Returns True if the string contains at least one letter and all characters are in lower case; otherwise it returns False isupper() Returns True if the string contains at least one letter and all characters are in upper case; otherwise it returns False istitle() Returns True if each word of the string starts with a capital letter and there at least one character in the string; otherwise it returns False isspace() Returns True if the string contains only spaces; otherwise, it returns False
  • 23. Strings And Characters Formatting the strings format() Presenting the string in the clearly understandable manner Syntax "format string with replacement fields". format(values) id = 10 name = "Ram" sal = 19000.45 print("{}, {}, {}". format(id, name, sal)) print("{}-{}-{}". format(id, name, sal)) print("ID: {0}tName: {1}tSal: {2}n". format(id, name, sal)) print("ID: {2}tName: {0}tSal: {1}n". format(id, name, sal)) print("ID: {two}tName: {zero}tSal: {one}n". format(zero=id, one=name, two=sal)) print("ID: {:d}tName: {:s}tSal: {:10.2f}n". format(id, name, sal))
  • 24. Strings And Characters Formatting the strings format() Presenting the string in the clearly understandable manner Syntax "format string with replacement fields". format(values) n = 5000 print("{:*>15d}". format(num)) print("{:*^15d}". format(num))
  • 25. Strings And Characters Exercise 1. To know the type of character entered by the user 2. To sort the strings in alphabetical order 3. To search for the position for a string in agiven group of strings 4. To find the number of words in a given strings 5. To insert the sub-string into a main string in a particular position