SlideShare a Scribd company logo
V.M.Prabhakaran,
Department Of Cse,
KIT- Coimbatore
Problem Solving and Python Programming 1
Strings: string slices, immutability,
string functions and methods, string
module
Problem Solving and Python Programming 2
Strings
• String is a sequence of characters.
• String may contain alphabets, numbers and
special characters.
• Usually strings are enclosed within a single
quotes and double quotes.
• Strings is immutable in nature.
• Example:
a=„hello world‟
b=“Python”
Problem Solving and Python Programming 3
Inbuilt String functions
• Python mainly contains 3 inbuilt string functions.
• They are
– len()
– max()
– min()
• len()- Find out the length of characters in string
• min()- Smallest value in a string based on ASCII values
• max()- Largest value in a string based on ASCII values
Problem Solving and Python Programming 4
What is ASCII values
Problem Solving and Python Programming 5
Example for Inbuilt string functions
name=input("Enter Your name:")
print("Welcome",name)
print("Length of your name:",len(name))
print("Maximum value of chararacter in your name",
max(name))
print("Minimum value of character in your name",min(name))
Problem Solving and Python Programming 6
OUTPUT
Enter Your name:PRABHAKARAN
Welcome PRABHAKARAN
Length of your name: 11
Maximum value of chararacter in your name R
Minimum value of character in your name A
Problem Solving and Python Programming 7
Strings Concatenation
• The + operator used for string concatenation.
Example:
a=“Hai”
b=“how are you”
c=a+b
print(c)
Problem Solving and Python Programming 8
Operators on String
• The Concatenate strings with the “*” operator
can create multiple concatenated copies.
• Example:
>>> print("Python"*10)
PythonPythonPythonPythonPythonPython
PythonPythonPythonPython
Problem Solving and Python Programming 9
String Slicing
• Slicing operation is used to return/select/slice
the particular substring based on user
requirements.
• A segment of string is called slice.
• Syntax: string_variablename [ start:end]
Problem Solving and Python Programming 10
String Slice example
s=“Hello”
Problem Solving and Python Programming 11
H e l l o
0 1 2 3 4
-5 -4 -3 -2 -1
Strings are immutable
• Strings are immutable character sets.
• Once a string is generated, you cannot change
any character within the string.
Problem Solving and Python Programming 12
String Comparision
• We can compare two strings using comparision
operators such as ==, !=, <,<=,>, >=
• Python compares strings based on their
corresponding ASCII values.
Problem Solving and Python Programming 13
Example of string comparision
str1="green"
str2="black"
print("Is both Equal:", str1==str2)
print("Is str1> str2:", str1>str2)
print("Is str1< str2:", str1<str2)
Problem Solving and Python Programming 14
OUTPUT:
Is both Equal: False
Is str1> str2: True
Is str1< str2: False
String formatting operator
• String formatting operator % is unique to
strings.
• Example:
print("My name is %s and i secured %d
marks in python” % ("Arbaz",92))
• Output:
My name is Arbaz and i secured 92 marks in
python
Problem Solving and Python Programming 15
String functions and methods
len() min() max() isalnum() isalpha()
isdigit() islower() isuppe() isspace() isidentifier()
endswith() startswith() find() count() capitalize()
title() lower() upper() swapcase() replace()
center() ljust() rjust() center() isstrip()
rstrip() strip()
Problem Solving and Python Programming 16
i) Converting string functions
Problem Solving and Python Programming 17
captitalize() Only First character capitalized
lower() All character converted to lowercase
upper() All character converted to uppercase
title() First character capitalized in each word
swapcase() Lower case letters are converted to
Uppercase and Uppercase letters are
converted to Lowercase
replace(old,new) Replaces old string with nre string
Program:
str=input("Enter any string:")
print("String Capitalized:", str.capitalize())
print("String lower case:", str.lower())
print("String upper case:", str.upper())
print("String title case:", str.title())
print("String swap case:", str.swapcase())
print("String replace case:",str.replace("python","python programming"))
Problem Solving and Python Programming 18
Output:
Enter any string: Welcome to python
String Capitalized: Welcome to python
String lower case: welcome to python
String upper case: WELCOME TO PYTHON
String title case: Welcome To Python
String swap case: wELCOME TO PYTHON
String replace case: Welcome to python programming
ii)Formatting String functions
Problem Solving and Python Programming 19
center(width) Returns a string centered in a field of given width
ljust(width) Returns a string left justified in a field of given width
rjust(width) Returns a string right justified in a field of given width
format(items) Formats a string
Program:
a=input("Enter any string:")
print("Center alignment:", a.center(20))
print("Left alignment:", a.ljust(20))
print("Right alignment:", a.rjust(20))
Problem Solving and Python Programming 20
Output:
iii) Removing whitespace
characters
Problem Solving and Python Programming 21
lstrip()
Returns a string with
leading whitespace
characters removed
rstrip()
Returns a string with
trailing whitespace
characters removed
strip()
Returns a string with
leading and trailing
whitespace characters
removed
Program
a=input("Enter any string:")
print("Left space trim:",a.lstrip())
print("Right space trim:",a.rstrip())
print("Left and right trim:",a.strip())
Problem Solving and Python Programming 22
Output:
iv) Testing String/Character
Problem Solving and Python Programming 23
isalnum()
Returns true if all characters in string are alphanumeric and there is
atleast one character
isalpha()
Returns true if all characters in string are alphabetic
isdigit()
Returns true if string contains only number character
islower()
Returns true if all characters in string are lowercase letters
isupper()
Returns true if all characters in string are uppercase letters
isspace() Returns true if string contains only whitespace characters.
Program
a=input("Enter any string:")
print("Alphanumeric:",a.isalnum())
print("Alphabetic:",a.isalpha())
print("Digits:",a.isdigit())
print("Lowecase:",a.islower())
print("Upper:",a.isupper())
Problem Solving and Python Programming 24
Output:
v) Searching for substring
Problem Solving and Python Programming 25
Endswith() Returns true if the strings ends with the substring
Startswith()
Returns true if the strings starts with the substring
Find()
Returns the lowest index or -1 if substring not found
Count() Returns the number of occurrences of substring
Program
a=input("Enter any string:")
print("Is string ends with thon:", a.endswith("thon"))
print("Is string starts with good:", a.startswith("good"))
print("Find:", a.find("ython"))
print("Count:", a.count(“o"))
Problem Solving and Python Programming 26
Output:
Enter any string : welcome to python
Is string ends with thon: True
Is string starts with good: False
Find: 12
Count: 3
String Modules
• String module contains a number of functions to
process standard Python strings
• Mostly used string modules:
string.upper()
string.upper()
string.split()
string.join()
string.replace()
string.find()
string.count()
Problem Solving and Python Programming 27
Example
import string
text="Monty Python Flying Circus"
print("Upper:", string.upper(text))
print("Lower:", string.lower(text))
print("Split:", string.split(text))
print("Join:", string.join(string.split(test),"+"))
print("Replace:", string.replace(text,"Python", "Java"))
print("Find:", string.find(text,"Python"))
print("Count", string.count(text,"n"))
Problem Solving and Python Programming 28
Output
Problem Solving and Python Programming 29
Upper: “MONTY PYTHON FLYING CIRCUS”
Lower: “monty python flying circus”
Split: [„Monty‟, „Python‟, „Flying‟, „Circus‟]
Join : Monty+Python+Flying+Circus
Replace: Monty Java Flying Circus
Find: 7
Count: 3

More Related Content

What's hot (20)

PDF
Applications of stack
eShikshak
 
ODP
Python Modules
Nitin Reddy Katkam
 
PDF
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
PDF
Datatypes in python
eShikshak
 
PDF
Python set
Mohammed Sikander
 
PPTX
Functions in Python
Shakti Singh Rathore
 
PPTX
Recursive Function
Harsh Pathak
 
PDF
Variables & Data Types In Python | Edureka
Edureka!
 
PDF
Operators in python
Prabhakaran V M
 
PPTX
Nested loops
Neeru Mittal
 
PPT
RECURSION IN C
v_jk
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
File handling in Python
Megha V
 
PPTX
Data Structures in Python
Devashish Kumar
 
PPTX
Functions in Python
Kamal Acharya
 
PPTX
Python dictionary
Sagar Kumar
 
PDF
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
PPTX
Array ppt
Kaushal Mehta
 
PDF
Python-03| Data types
Mohd Sajjad
 
PDF
Arrays in python
moazamali28
 
Applications of stack
eShikshak
 
Python Modules
Nitin Reddy Katkam
 
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Datatypes in python
eShikshak
 
Python set
Mohammed Sikander
 
Functions in Python
Shakti Singh Rathore
 
Recursive Function
Harsh Pathak
 
Variables & Data Types In Python | Edureka
Edureka!
 
Operators in python
Prabhakaran V M
 
Nested loops
Neeru Mittal
 
RECURSION IN C
v_jk
 
Python: Modules and Packages
Damian T. Gordon
 
File handling in Python
Megha V
 
Data Structures in Python
Devashish Kumar
 
Functions in Python
Kamal Acharya
 
Python dictionary
Sagar Kumar
 
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Array ppt
Kaushal Mehta
 
Python-03| Data types
Mohd Sajjad
 
Arrays in python
moazamali28
 

Similar to Strings in python (20)

PDF
stringsinpython-181122100212.pdf
paijitk
 
PPTX
STRINGS_IN_PYTHON 9-12 (1).pptx
Tinku91
 
PPTX
UNIT 4 python.pptx
TKSanthoshRao
 
PDF
Python- strings
Krishna Nanda
 
PPTX
trisha comp ppt.pptx
Tapaswini14
 
PPTX
Python Strings.pptx
adityakumawat625
 
PPTX
Python Strings and its Featues Explained in Detail .pptx
parmg0960
 
PPTX
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
rajvishnuf9
 
PDF
Strings brief introduction in python.pdf
TODAYIREAD1
 
PPTX
Unit_I-Introduction python programming (1).pptx
arunbalaji707
 
PDF
ppt notes python language operators and data
SukhpreetSingh519414
 
PDF
Python data handling
Prof. Dr. K. Adisesha
 
PDF
String.pdf
PritamKumar293071
 
PPT
PPS_Unit 4.ppt
KundanBhatkar
 
PPTX
Engineering string(681) concept ppt.pptx
ChandrashekarReddy98
 
PPTX
STRINGS IN PYTHON
TanushTM1
 
PDF
strings in python (presentation for DSA)
MirzaAbdullahTariq
 
PPTX
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
PPTX
stringggg.pptxtujd7ttttttttttttttttttttttttttttttttttt
pawankamal3
 
PPT
Chapter05.ppt
afsheenfaiq2
 
stringsinpython-181122100212.pdf
paijitk
 
STRINGS_IN_PYTHON 9-12 (1).pptx
Tinku91
 
UNIT 4 python.pptx
TKSanthoshRao
 
Python- strings
Krishna Nanda
 
trisha comp ppt.pptx
Tapaswini14
 
Python Strings.pptx
adityakumawat625
 
Python Strings and its Featues Explained in Detail .pptx
parmg0960
 
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
rajvishnuf9
 
Strings brief introduction in python.pdf
TODAYIREAD1
 
Unit_I-Introduction python programming (1).pptx
arunbalaji707
 
ppt notes python language operators and data
SukhpreetSingh519414
 
Python data handling
Prof. Dr. K. Adisesha
 
String.pdf
PritamKumar293071
 
PPS_Unit 4.ppt
KundanBhatkar
 
Engineering string(681) concept ppt.pptx
ChandrashekarReddy98
 
STRINGS IN PYTHON
TanushTM1
 
strings in python (presentation for DSA)
MirzaAbdullahTariq
 
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
stringggg.pptxtujd7ttttttttttttttttttttttttttttttttttt
pawankamal3
 
Chapter05.ppt
afsheenfaiq2
 
Ad

More from Prabhakaran V M (7)

PDF
Algorithmic problem solving
Prabhakaran V M
 
PDF
Open mp directives
Prabhakaran V M
 
PDF
Xml schema
Prabhakaran V M
 
PDF
Html 5
Prabhakaran V M
 
PDF
Introduction to Multi-core Architectures
Prabhakaran V M
 
PDF
Java threads
Prabhakaran V M
 
PDF
Applets
Prabhakaran V M
 
Algorithmic problem solving
Prabhakaran V M
 
Open mp directives
Prabhakaran V M
 
Xml schema
Prabhakaran V M
 
Introduction to Multi-core Architectures
Prabhakaran V M
 
Java threads
Prabhakaran V M
 
Ad

Recently uploaded (20)

PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
GridView,Recycler view, API, SQLITE& NetworkRequest.pdf
Nabin Dhakal
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
GridView,Recycler view, API, SQLITE& NetworkRequest.pdf
Nabin Dhakal
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 

Strings in python

  • 1. V.M.Prabhakaran, Department Of Cse, KIT- Coimbatore Problem Solving and Python Programming 1
  • 2. Strings: string slices, immutability, string functions and methods, string module Problem Solving and Python Programming 2
  • 3. Strings • String is a sequence of characters. • String may contain alphabets, numbers and special characters. • Usually strings are enclosed within a single quotes and double quotes. • Strings is immutable in nature. • Example: a=„hello world‟ b=“Python” Problem Solving and Python Programming 3
  • 4. Inbuilt String functions • Python mainly contains 3 inbuilt string functions. • They are – len() – max() – min() • len()- Find out the length of characters in string • min()- Smallest value in a string based on ASCII values • max()- Largest value in a string based on ASCII values Problem Solving and Python Programming 4
  • 5. What is ASCII values Problem Solving and Python Programming 5
  • 6. Example for Inbuilt string functions name=input("Enter Your name:") print("Welcome",name) print("Length of your name:",len(name)) print("Maximum value of chararacter in your name", max(name)) print("Minimum value of character in your name",min(name)) Problem Solving and Python Programming 6
  • 7. OUTPUT Enter Your name:PRABHAKARAN Welcome PRABHAKARAN Length of your name: 11 Maximum value of chararacter in your name R Minimum value of character in your name A Problem Solving and Python Programming 7
  • 8. Strings Concatenation • The + operator used for string concatenation. Example: a=“Hai” b=“how are you” c=a+b print(c) Problem Solving and Python Programming 8
  • 9. Operators on String • The Concatenate strings with the “*” operator can create multiple concatenated copies. • Example: >>> print("Python"*10) PythonPythonPythonPythonPythonPython PythonPythonPythonPython Problem Solving and Python Programming 9
  • 10. String Slicing • Slicing operation is used to return/select/slice the particular substring based on user requirements. • A segment of string is called slice. • Syntax: string_variablename [ start:end] Problem Solving and Python Programming 10
  • 11. String Slice example s=“Hello” Problem Solving and Python Programming 11 H e l l o 0 1 2 3 4 -5 -4 -3 -2 -1
  • 12. Strings are immutable • Strings are immutable character sets. • Once a string is generated, you cannot change any character within the string. Problem Solving and Python Programming 12
  • 13. String Comparision • We can compare two strings using comparision operators such as ==, !=, <,<=,>, >= • Python compares strings based on their corresponding ASCII values. Problem Solving and Python Programming 13
  • 14. Example of string comparision str1="green" str2="black" print("Is both Equal:", str1==str2) print("Is str1> str2:", str1>str2) print("Is str1< str2:", str1<str2) Problem Solving and Python Programming 14 OUTPUT: Is both Equal: False Is str1> str2: True Is str1< str2: False
  • 15. String formatting operator • String formatting operator % is unique to strings. • Example: print("My name is %s and i secured %d marks in python” % ("Arbaz",92)) • Output: My name is Arbaz and i secured 92 marks in python Problem Solving and Python Programming 15
  • 16. String functions and methods len() min() max() isalnum() isalpha() isdigit() islower() isuppe() isspace() isidentifier() endswith() startswith() find() count() capitalize() title() lower() upper() swapcase() replace() center() ljust() rjust() center() isstrip() rstrip() strip() Problem Solving and Python Programming 16
  • 17. i) Converting string functions Problem Solving and Python Programming 17 captitalize() Only First character capitalized lower() All character converted to lowercase upper() All character converted to uppercase title() First character capitalized in each word swapcase() Lower case letters are converted to Uppercase and Uppercase letters are converted to Lowercase replace(old,new) Replaces old string with nre string
  • 18. Program: str=input("Enter any string:") print("String Capitalized:", str.capitalize()) print("String lower case:", str.lower()) print("String upper case:", str.upper()) print("String title case:", str.title()) print("String swap case:", str.swapcase()) print("String replace case:",str.replace("python","python programming")) Problem Solving and Python Programming 18 Output: Enter any string: Welcome to python String Capitalized: Welcome to python String lower case: welcome to python String upper case: WELCOME TO PYTHON String title case: Welcome To Python String swap case: wELCOME TO PYTHON String replace case: Welcome to python programming
  • 19. ii)Formatting String functions Problem Solving and Python Programming 19 center(width) Returns a string centered in a field of given width ljust(width) Returns a string left justified in a field of given width rjust(width) Returns a string right justified in a field of given width format(items) Formats a string
  • 20. Program: a=input("Enter any string:") print("Center alignment:", a.center(20)) print("Left alignment:", a.ljust(20)) print("Right alignment:", a.rjust(20)) Problem Solving and Python Programming 20 Output:
  • 21. iii) Removing whitespace characters Problem Solving and Python Programming 21 lstrip() Returns a string with leading whitespace characters removed rstrip() Returns a string with trailing whitespace characters removed strip() Returns a string with leading and trailing whitespace characters removed
  • 22. Program a=input("Enter any string:") print("Left space trim:",a.lstrip()) print("Right space trim:",a.rstrip()) print("Left and right trim:",a.strip()) Problem Solving and Python Programming 22 Output:
  • 23. iv) Testing String/Character Problem Solving and Python Programming 23 isalnum() Returns true if all characters in string are alphanumeric and there is atleast one character isalpha() Returns true if all characters in string are alphabetic isdigit() Returns true if string contains only number character islower() Returns true if all characters in string are lowercase letters isupper() Returns true if all characters in string are uppercase letters isspace() Returns true if string contains only whitespace characters.
  • 25. v) Searching for substring Problem Solving and Python Programming 25 Endswith() Returns true if the strings ends with the substring Startswith() Returns true if the strings starts with the substring Find() Returns the lowest index or -1 if substring not found Count() Returns the number of occurrences of substring
  • 26. Program a=input("Enter any string:") print("Is string ends with thon:", a.endswith("thon")) print("Is string starts with good:", a.startswith("good")) print("Find:", a.find("ython")) print("Count:", a.count(“o")) Problem Solving and Python Programming 26 Output: Enter any string : welcome to python Is string ends with thon: True Is string starts with good: False Find: 12 Count: 3
  • 27. String Modules • String module contains a number of functions to process standard Python strings • Mostly used string modules: string.upper() string.upper() string.split() string.join() string.replace() string.find() string.count() Problem Solving and Python Programming 27
  • 28. Example import string text="Monty Python Flying Circus" print("Upper:", string.upper(text)) print("Lower:", string.lower(text)) print("Split:", string.split(text)) print("Join:", string.join(string.split(test),"+")) print("Replace:", string.replace(text,"Python", "Java")) print("Find:", string.find(text,"Python")) print("Count", string.count(text,"n")) Problem Solving and Python Programming 28
  • 29. Output Problem Solving and Python Programming 29 Upper: “MONTY PYTHON FLYING CIRCUS” Lower: “monty python flying circus” Split: [„Monty‟, „Python‟, „Flying‟, „Circus‟] Join : Monty+Python+Flying+Circus Replace: Monty Java Flying Circus Find: 7 Count: 3