SlideShare a Scribd company logo
Python Strings
1. Slicing Strings
2. Modify Strings
3. Concatenate Strings
4. Format Strings
5. Escape Strings
Prof. Kartiki Deshmukh
•Strings in python are surrounded by either single quotation
marks, or double quotation marks.
•'hello' is the same as "hello".
•You can display a string literal with the print() function.
You can use double or single quotes:
print("Hello")
print('Hello')
Output:
Hello
Hello
Prof. Kartiki Deshmukh
Quotes Inside Quotes
You can use quotes inside a string, as long as they don't
match the quotes surrounding the string.
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Output:
It's alright
He is called 'Johnny'
He is called "Johnny"
Prof. Kartiki Deshmukh
Assign String to a Variable
Assigning a string to a variable is done with the variable name
followed by an equal sign and the string.
a = "Hello"
print(a)
Output:
Hello
Prof. Kartiki Deshmukh
Multiline Strings
You can assign a multiline string to a variable by using
three quotes.
a = """Modern College
of arts, science and commerce,
Shivajinagar, Pune"""
print(a)
Output:
Modern College
of arts, science and commerce,
Shivajinagar, Pune Prof. Kartiki Deshmukh
Strings are Arrays
•Like many other popular programming languages, strings
in Python are arrays of bytes representing unicode
characters.
•However, Python does not have a character data type, a
single character is simply a string with a length of 1.
•Square brackets can be used to access elements of the
string.
a = "Hello, World!"
print(a[1])
Output:
e
Prof. Kartiki Deshmukh
Looping Through a String
Since strings are arrays, we can loop through the
characters in a string, with a for loop.
for x in ‘mango’:
print(x)
Output:
m
a
n
g
o
Prof. Kartiki Deshmukh
String Length
To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
Output:
13
Prof. Kartiki Deshmukh
Check String
To check if a certain phrase or character is present in a string,
we can use the keyword in.
txt = "The best things in life are free!"
print("free" in txt)
Output:
True
Prof. Kartiki Deshmukh
Use it in an if statement:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Output:
Yes, 'free' is present.
Prof. Kartiki Deshmukh
Check if NOT
To check if a certain phrase or character is NOT present in
a string, we can use the keyword not in.
txt = "The best things in life are free!"
print("expensive" not in txt)
Output:
True
Prof. Kartiki Deshmukh
Slicing Strings
You can return a range of characters by using the slice
syntax.
Specify the start index and the end index, separated by a
colon, to return a part of the string.
b = "Hello, World!"
print(b[2:5])
Output:
llo
Prof. Kartiki Deshmukh
Slice From the Start
By leaving out the start index, the range will start at the
first character.
b = "Hello, World!"
print(b[:5])
Output:
Hello
Prof. Kartiki Deshmukh
Slice To the End
By leaving out the end index, the range will go to the end.
b = "Hello, World!"
print(b[2:])
llo, World!
Prof. Kartiki Deshmukh
Negative Indexing
Use negative indexes to start the slice from the end of
the string.
b = "Hello, World!"
print(b[-5:-2])
Output:
orl
Note: From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2)
Prof. Kartiki Deshmukh
Modify Strings
1. Upper Case
The upper() method returns the string in upper case.
a = "Hello, World!"
print(a.upper())
Output:
HELLO, WORLD!
Prof. Kartiki Deshmukh
2. Lower Case
The lower() method returns the string in lower case.
a = "Hello, World!"
print(a.lower())
Output:
hello, world!
Prof. Kartiki Deshmukh
3. Remove Whitespace
Whitespace is the space before and/or after the actual
text, and very often you want to remove this space.
The strip() method removes any whitespace from the
beginning or the end.
a = " Hello, World! "
print(a.strip())
Output:
Hello, World!
Prof. Kartiki Deshmukh
4. Replace String
The replace() method replaces a string with another string.
a = "Hello, World!"
print(a.replace("H", "J"))
Output:
Jello, World!
Prof. Kartiki Deshmukh
5. Split String
The split() method returns a list where the text
between the specified separator becomes the list
items.
a = "Hello, World!"
print(a.split(","))
Output:
['Hello', ' World!']
Prof. Kartiki Deshmukh
String Concatenation
To concatenate, or combine, two strings you can use the +
operator.
a = "Hello"
b = "World"
c = a + b
print(c)
Output:
HelloWorld
To add a space between them, add a " “.
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Output:
Hello World
Prof. Kartiki Deshmukh
Format Strings
As we learned in the Python Variables chapter, we
cannot combine strings and numbers, but we can
combine strings and numbers by using f-strings or
the format() method.
To specify a string as an f-string, simply put an f in front
of the string literal, and add curly brackets {} as
placeholders for variables and other operations.
Prof. Kartiki Deshmukh
age = 36
txt = f"My name is John, I am {age}"
print(txt)
Output:
My name is John, I am 36
Prof. Kartiki Deshmukh
Placeholders and Modifiers
A placeholder can contain variables, operations, functions,
and modifiers to format the value.
price = 59
txt = f"The price is {price} dollars"
print(txt)
Output:
The price is 59 dollars
Prof. Kartiki Deshmukh
A placeholder can include a modifier to format the value.
A modifier is included by adding a colon : followed by a
legal formatting type, like .2f which means fixed point
number with 2 decimals.
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Output:
The price is 59.00 dollars
Prof. Kartiki Deshmukh
A placeholder can contain Python code, like math
operations.
txt = f"The price is {20 * 59} dollars"
print(txt)
Output:
The price is 1180 dollars
Prof. Kartiki Deshmukh
Escape Characters
To insert characters that are illegal in a string, use an escape
character.
An escape character is a backslash  followed by the
character you want to insert.
The escape character allows you to use double quotes when
you normally would not be allowed.
txt = "We are the so-called "Vikings" from the north.“
Output:
We are the so-called "Vikings" from the north.
Prof. Kartiki Deshmukh
Code Result
' Single Quote
 Backslash
n New Line
r Carriage Return
t Tab
b Backspace
f Form Feed
ooo Octal value
xhh Hex value
Escape Characters
Other escape characters used in Python.
Prof. Kartiki Deshmukh

More Related Content

Similar to Python Strings and strings types with Examples (20)

Python- strings
Python- stringsPython- strings
Python- strings
Krishna Nanda
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
TanushTM1
 
strings in python (presentation for DSA)
strings in python (presentation for DSA)strings in python (presentation for DSA)
strings in python (presentation for DSA)
MirzaAbdullahTariq
 
python_strings.pdf
python_strings.pdfpython_strings.pdf
python_strings.pdf
rajendraprasadbabub1
 
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoiiStrings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
pawankamal3
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdfpython1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPTPROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
factsandknowledge94
 
PPS_Unit 4.ppt
PPS_Unit 4.pptPPS_Unit 4.ppt
PPS_Unit 4.ppt
KundanBhatkar
 
Python String Revisited.pptx
Python String Revisited.pptxPython String Revisited.pptx
Python String Revisited.pptx
Chandrapriya Jayabal
 
Day5 String python language for btech.pptx
Day5 String python language for btech.pptxDay5 String python language for btech.pptx
Day5 String python language for btech.pptx
mrsam3062
 
Different uses of String in Python.pptx
Different uses of  String in Python.pptxDifferent uses of  String in Python.pptx
Different uses of String in Python.pptx
AryadipDey
 
Python basics
Python basicsPython basics
Python basics
Hoang Nguyen
 
Python basics
Python basicsPython basics
Python basics
Luis Goldster
 
Python basics
Python basicsPython basics
Python basics
Tony Nguyen
 
Python basics
Python basicsPython basics
Python basics
Fraboni Ec
 
Python basics
Python basicsPython basics
Python basics
Harry Potter
 
Python basics
Python basicsPython basics
Python basics
Young Alista
 
Python basics
Python basicsPython basics
Python basics
James Wong
 
foundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptxfoundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptx
MarufFarhanRigan1
 
Strings.pptx
Strings.pptxStrings.pptx
Strings.pptx
Yagna15
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
TanushTM1
 
strings in python (presentation for DSA)
strings in python (presentation for DSA)strings in python (presentation for DSA)
strings in python (presentation for DSA)
MirzaAbdullahTariq
 
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoiiStrings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
pawankamal3
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdfpython1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPTPROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
factsandknowledge94
 
Day5 String python language for btech.pptx
Day5 String python language for btech.pptxDay5 String python language for btech.pptx
Day5 String python language for btech.pptx
mrsam3062
 
Different uses of String in Python.pptx
Different uses of  String in Python.pptxDifferent uses of  String in Python.pptx
Different uses of String in Python.pptx
AryadipDey
 
foundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptxfoundation class python week 4- Strings.pptx
foundation class python week 4- Strings.pptx
MarufFarhanRigan1
 
Strings.pptx
Strings.pptxStrings.pptx
Strings.pptx
Yagna15
 

Recently uploaded (20)

Understanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User InterviewsUnderstanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User Interviews
sehilyi
 
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdfHOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
Faga1939
 
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrerAgriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
kanopatel8840
 
Aquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdfAquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdf
camillemaguid53
 
Introduction to Microbiology and Microscope
Introduction to Microbiology and MicroscopeIntroduction to Microbiology and Microscope
Introduction to Microbiology and Microscope
vaishrawan1
 
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdfBOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
zap6635
 
International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)
journalijps98
 
chemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdfchemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdf
s99808177
 
Telehealth For Maternal and Child Health: Expanding Access (www.kiu.ac.ug)
Telehealth For Maternal and Child Health: Expanding  Access (www.kiu.ac.ug)Telehealth For Maternal and Child Health: Expanding  Access (www.kiu.ac.ug)
Telehealth For Maternal and Child Health: Expanding Access (www.kiu.ac.ug)
publication11
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
National development you must learn it.pptx
National development you must learn it.pptxNational development you must learn it.pptx
National development you must learn it.pptx
mukherjeechetan56
 
the presentation on downstream processing (DSP).pptx
the presentation on downstream processing (DSP).pptxthe presentation on downstream processing (DSP).pptx
the presentation on downstream processing (DSP).pptx
aanchalm373
 
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjjRadiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Debaprasad16
 
Morphological and biochemical characterization in Rice
Morphological and biochemical characterization in RiceMorphological and biochemical characterization in Rice
Morphological and biochemical characterization in Rice
AbhishekChauhan911496
 
Struktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetikaStruktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetika
WiwitProbowati2
 
Entomopath angrau third year path 365pdf
Entomopath angrau third year path 365pdfEntomopath angrau third year path 365pdf
Entomopath angrau third year path 365pdf
zap6635
 
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Dr.Devraj Neupane
 
Comparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebratesComparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebrates
arpanmaji480
 
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRAAlgebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
ropamadoda
 
the presentation on pyruvate dehydrogenase complex (PDH).pptx
the presentation on pyruvate dehydrogenase complex (PDH).pptxthe presentation on pyruvate dehydrogenase complex (PDH).pptx
the presentation on pyruvate dehydrogenase complex (PDH).pptx
aanchalm373
 
Understanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User InterviewsUnderstanding Visualization Authoring for Genomics Data through User Interviews
Understanding Visualization Authoring for Genomics Data through User Interviews
sehilyi
 
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdfHOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
Faga1939
 
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrerAgriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
kanopatel8840
 
Aquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdfAquatic ecosystem and its biomes involved.pdf
Aquatic ecosystem and its biomes involved.pdf
camillemaguid53
 
Introduction to Microbiology and Microscope
Introduction to Microbiology and MicroscopeIntroduction to Microbiology and Microscope
Introduction to Microbiology and Microscope
vaishrawan1
 
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdfBOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
zap6635
 
International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)International Journal of Pharmacological Sciences (IJPS)
International Journal of Pharmacological Sciences (IJPS)
journalijps98
 
chemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdfchemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdf
s99808177
 
Telehealth For Maternal and Child Health: Expanding Access (www.kiu.ac.ug)
Telehealth For Maternal and Child Health: Expanding  Access (www.kiu.ac.ug)Telehealth For Maternal and Child Health: Expanding  Access (www.kiu.ac.ug)
Telehealth For Maternal and Child Health: Expanding Access (www.kiu.ac.ug)
publication11
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
National development you must learn it.pptx
National development you must learn it.pptxNational development you must learn it.pptx
National development you must learn it.pptx
mukherjeechetan56
 
the presentation on downstream processing (DSP).pptx
the presentation on downstream processing (DSP).pptxthe presentation on downstream processing (DSP).pptx
the presentation on downstream processing (DSP).pptx
aanchalm373
 
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjjRadiation pressure (1).tygfyhjjjbcdssfvvjj
Radiation pressure (1).tygfyhjjjbcdssfvvjj
Debaprasad16
 
Morphological and biochemical characterization in Rice
Morphological and biochemical characterization in RiceMorphological and biochemical characterization in Rice
Morphological and biochemical characterization in Rice
AbhishekChauhan911496
 
Struktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetikaStruktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetika
WiwitProbowati2
 
Entomopath angrau third year path 365pdf
Entomopath angrau third year path 365pdfEntomopath angrau third year path 365pdf
Entomopath angrau third year path 365pdf
zap6635
 
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Dr.Devraj Neupane
 
Comparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebratesComparative anatomy of brain of different types of vertebrates
Comparative anatomy of brain of different types of vertebrates
arpanmaji480
 
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRAAlgebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
ropamadoda
 
the presentation on pyruvate dehydrogenase complex (PDH).pptx
the presentation on pyruvate dehydrogenase complex (PDH).pptxthe presentation on pyruvate dehydrogenase complex (PDH).pptx
the presentation on pyruvate dehydrogenase complex (PDH).pptx
aanchalm373
 
Ad

Python Strings and strings types with Examples

  • 1. Python Strings 1. Slicing Strings 2. Modify Strings 3. Concatenate Strings 4. Format Strings 5. Escape Strings Prof. Kartiki Deshmukh
  • 2. •Strings in python are surrounded by either single quotation marks, or double quotation marks. •'hello' is the same as "hello". •You can display a string literal with the print() function. You can use double or single quotes: print("Hello") print('Hello') Output: Hello Hello Prof. Kartiki Deshmukh
  • 3. Quotes Inside Quotes You can use quotes inside a string, as long as they don't match the quotes surrounding the string. print("It's alright") print("He is called 'Johnny'") print('He is called "Johnny"') Output: It's alright He is called 'Johnny' He is called "Johnny" Prof. Kartiki Deshmukh
  • 4. Assign String to a Variable Assigning a string to a variable is done with the variable name followed by an equal sign and the string. a = "Hello" print(a) Output: Hello Prof. Kartiki Deshmukh
  • 5. Multiline Strings You can assign a multiline string to a variable by using three quotes. a = """Modern College of arts, science and commerce, Shivajinagar, Pune""" print(a) Output: Modern College of arts, science and commerce, Shivajinagar, Pune Prof. Kartiki Deshmukh
  • 6. Strings are Arrays •Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. •However, Python does not have a character data type, a single character is simply a string with a length of 1. •Square brackets can be used to access elements of the string. a = "Hello, World!" print(a[1]) Output: e Prof. Kartiki Deshmukh
  • 7. Looping Through a String Since strings are arrays, we can loop through the characters in a string, with a for loop. for x in ‘mango’: print(x) Output: m a n g o Prof. Kartiki Deshmukh
  • 8. String Length To get the length of a string, use the len() function. a = "Hello, World!" print(len(a)) Output: 13 Prof. Kartiki Deshmukh
  • 9. Check String To check if a certain phrase or character is present in a string, we can use the keyword in. txt = "The best things in life are free!" print("free" in txt) Output: True Prof. Kartiki Deshmukh
  • 10. Use it in an if statement: txt = "The best things in life are free!" if "free" in txt: print("Yes, 'free' is present.") Output: Yes, 'free' is present. Prof. Kartiki Deshmukh
  • 11. Check if NOT To check if a certain phrase or character is NOT present in a string, we can use the keyword not in. txt = "The best things in life are free!" print("expensive" not in txt) Output: True Prof. Kartiki Deshmukh
  • 12. Slicing Strings You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string. b = "Hello, World!" print(b[2:5]) Output: llo Prof. Kartiki Deshmukh
  • 13. Slice From the Start By leaving out the start index, the range will start at the first character. b = "Hello, World!" print(b[:5]) Output: Hello Prof. Kartiki Deshmukh
  • 14. Slice To the End By leaving out the end index, the range will go to the end. b = "Hello, World!" print(b[2:]) llo, World! Prof. Kartiki Deshmukh
  • 15. Negative Indexing Use negative indexes to start the slice from the end of the string. b = "Hello, World!" print(b[-5:-2]) Output: orl Note: From: "o" in "World!" (position -5) To, but not included: "d" in "World!" (position -2) Prof. Kartiki Deshmukh
  • 16. Modify Strings 1. Upper Case The upper() method returns the string in upper case. a = "Hello, World!" print(a.upper()) Output: HELLO, WORLD! Prof. Kartiki Deshmukh
  • 17. 2. Lower Case The lower() method returns the string in lower case. a = "Hello, World!" print(a.lower()) Output: hello, world! Prof. Kartiki Deshmukh
  • 18. 3. Remove Whitespace Whitespace is the space before and/or after the actual text, and very often you want to remove this space. The strip() method removes any whitespace from the beginning or the end. a = " Hello, World! " print(a.strip()) Output: Hello, World! Prof. Kartiki Deshmukh
  • 19. 4. Replace String The replace() method replaces a string with another string. a = "Hello, World!" print(a.replace("H", "J")) Output: Jello, World! Prof. Kartiki Deshmukh
  • 20. 5. Split String The split() method returns a list where the text between the specified separator becomes the list items. a = "Hello, World!" print(a.split(",")) Output: ['Hello', ' World!'] Prof. Kartiki Deshmukh
  • 21. String Concatenation To concatenate, or combine, two strings you can use the + operator. a = "Hello" b = "World" c = a + b print(c) Output: HelloWorld To add a space between them, add a " “. a = "Hello" b = "World" c = a + " " + b print(c) Output: Hello World Prof. Kartiki Deshmukh
  • 22. Format Strings As we learned in the Python Variables chapter, we cannot combine strings and numbers, but we can combine strings and numbers by using f-strings or the format() method. To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations. Prof. Kartiki Deshmukh
  • 23. age = 36 txt = f"My name is John, I am {age}" print(txt) Output: My name is John, I am 36 Prof. Kartiki Deshmukh
  • 24. Placeholders and Modifiers A placeholder can contain variables, operations, functions, and modifiers to format the value. price = 59 txt = f"The price is {price} dollars" print(txt) Output: The price is 59 dollars Prof. Kartiki Deshmukh
  • 25. A placeholder can include a modifier to format the value. A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals. price = 59 txt = f"The price is {price:.2f} dollars" print(txt) Output: The price is 59.00 dollars Prof. Kartiki Deshmukh
  • 26. A placeholder can contain Python code, like math operations. txt = f"The price is {20 * 59} dollars" print(txt) Output: The price is 1180 dollars Prof. Kartiki Deshmukh
  • 27. Escape Characters To insert characters that are illegal in a string, use an escape character. An escape character is a backslash followed by the character you want to insert. The escape character allows you to use double quotes when you normally would not be allowed. txt = "We are the so-called "Vikings" from the north.“ Output: We are the so-called "Vikings" from the north. Prof. Kartiki Deshmukh
  • 28. Code Result ' Single Quote Backslash n New Line r Carriage Return t Tab b Backspace f Form Feed ooo Octal value xhh Hex value Escape Characters Other escape characters used in Python. Prof. Kartiki Deshmukh