SlideShare a Scribd company logo
1 of 29
Python Strings
Contents
• Introduction to Strings
• Features of Strings
• String Operation
• Methods of Strings
Strings
• A String is a data structure in Python that represents a sequence of
characters.
• It is an immutable data type, meaning that once you have created a
string, you cannot change it.
• Strings are used widely in many different applications, such as storing
and manipulating text data, representing names, addresses, and
other types of data that can be represented as text.
• Python does not have a character data type, a single character is
simply a string with a length of 1.
Creating Strings in Python
• 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:
print("Hello")
print('Hello')
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)
Multiline Strings
• You can assign a multiline string to a variable by using three quotes:
• You can use three double quotes:
a = """You can assign a multiline string,
to a variable by using,
three quotes """
print(a)
Strings are Arrays
• Strings in Python are arrays of bytes representing Unicode characters.
• 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.
• Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
• OUTPUT: e
Looping Through a String
• Since strings are arrays, we can loop through the characters in a
string, with a for loop.
• Loop through the letters in the word "banana":
for x in "banana":
print(x)
Features of Python Strings
• Python strings are "immutable" which means they cannot be changed
after they are created (Java strings also use this immutable style).
• Since strings can't be changed, we construct *new* strings as we go
to represent computed values.
• So for example the expression ('hello' + 'there') takes in the 2 strings
'hello' and 'there' and builds a new string 'hellothere'.
Features of Python Strings
• Characters in a string can be accessed using the standard [ ] syntax.
• Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'.
• If the index is out of bounds for the string, Python raises an error.
Accessing characters in Python String
• In Python, individual characters of a String can be accessed by using the
method of Indexing. Indexing allows negative address references to access
characters from the back of the String, e.g. -1 refers to the last character, -2
refers to the second last character, and so on.
• While accessing an index out of the range will cause an IndexError. Only
Integers are allowed to be passed as an index, float or other types that will
cause a TypeError.
String Length
• To get the length of a string, use the len() function.
• The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
OUTPUT: 13
Check String
• To check if a certain phrase or character is present in a string, we can use
the keyword in.
• Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
OUTPUT: True
• Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
OUTPUT: Yes, 'free' is present.
Check if NOT
• To check if a certain phrase or character is NOT present in a string, we can
use the keyword not in.
• Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
OUTPUT: True
• print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Slicing Strings
Slicing
• 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.
• Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Note: The first character has index 0.
OUTPUT: llo
Slice From the Start
• By leaving out the start index, the range will start at the first
character:
• Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Slice To the End
• By leaving out the end index, the range will go to the end:
• Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Negative Indexing
• Use negative indexes to start the slice from the end of the string:
Get the characters:
• From: "o" in "World!" (position -5)
• To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
OUTPUT: orl
Modify Strings
• Python has a set of built-in methods that you can use on strings.
UPPER CASE
• The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Output: HELLO, WORLD!
LOWER CASE
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Output: hello, world!
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!
Replace String
• The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Output: Jello, World!
Split String
• The split() method returns a list where the text between the specified
separator becomes the list items.
• The split() method splits the string into substrings if it finds instances of
the separator:
a ="Hello, World!"
print(a.split(","))
OUTPUT: ['Hello', ' World!']
String Concatenation
• To concatenate, or combine, two strings you can use the + operator.
• Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
Output: HelloWorld
String Concatenation
• To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
String Format
• In Python we cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are.
String Format
• Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Output: My name is John, and I am 36
String Format
The format() method takes unlimited number of arguments, and are placed
into the respective placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
OUTPUT: I want 3 pieces of item 567 for 49.95 dollars.
String Format
• You can use index numbers {0} to be sure the arguments are placed in
the correct placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Output: I want to pay 49.95 dollars for 3 pieces of item 567
capitalize() Method
• Upper case the first letter in this sentence:
txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)
OUTPUT: Hello, and welcome to my world.

More Related Content

Similar to Python Strings and its Featues Explained in Detail .pptx

String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxNimrahafzal1
 
STRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxSTRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxTinku91
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxhardii0991
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentationVedaGayathri1
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHONTanushTM1
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxJStalinAsstProfessor
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptxssuserc755f1
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
characters_strings.pdf
characters_strings.pdfcharacters_strings.pdf
characters_strings.pdfHoPeTaylor7
 
Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxlemonchoos
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptxPadreBhoj
 

Similar to Python Strings and its Featues Explained in Detail .pptx (20)

Python ppt
Python pptPython ppt
Python ppt
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
 
STRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxSTRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptx
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptx
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Chapter05.ppt
Chapter05.pptChapter05.ppt
Chapter05.ppt
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptx
 
Python- strings
Python- stringsPython- strings
Python- strings
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
M C6java7
M C6java7M C6java7
M C6java7
 
characters_strings.pdf
characters_strings.pdfcharacters_strings.pdf
characters_strings.pdf
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptx
 
Chapter 4 strings
Chapter 4 stringsChapter 4 strings
Chapter 4 strings
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 

Recently uploaded

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Python Strings and its Featues Explained in Detail .pptx

  • 2. Contents • Introduction to Strings • Features of Strings • String Operation • Methods of Strings
  • 3. Strings • A String is a data structure in Python that represents a sequence of characters. • It is an immutable data type, meaning that once you have created a string, you cannot change it. • Strings are used widely in many different applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text. • Python does not have a character data type, a single character is simply a string with a length of 1.
  • 4. Creating Strings in Python • 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: print("Hello") print('Hello')
  • 5. 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)
  • 6. Multiline Strings • You can assign a multiline string to a variable by using three quotes: • You can use three double quotes: a = """You can assign a multiline string, to a variable by using, three quotes """ print(a)
  • 7. Strings are Arrays • Strings in Python are arrays of bytes representing Unicode characters. • 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. • Get the character at position 1 (remember that the first character has the position 0): a = "Hello, World!" print(a[1]) • OUTPUT: e
  • 8. Looping Through a String • Since strings are arrays, we can loop through the characters in a string, with a for loop. • Loop through the letters in the word "banana": for x in "banana": print(x)
  • 9. Features of Python Strings • Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). • Since strings can't be changed, we construct *new* strings as we go to represent computed values. • So for example the expression ('hello' + 'there') takes in the 2 strings 'hello' and 'there' and builds a new string 'hellothere'.
  • 10. Features of Python Strings • Characters in a string can be accessed using the standard [ ] syntax. • Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'. • If the index is out of bounds for the string, Python raises an error. Accessing characters in Python String • In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on. • While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types that will cause a TypeError.
  • 11. String Length • To get the length of a string, use the len() function. • The len() function returns the length of a string: a = "Hello, World!" print(len(a)) OUTPUT: 13
  • 12. Check String • To check if a certain phrase or character is present in a string, we can use the keyword in. • Check if "free" is present in the following text: txt = "The best things in life are free!" print("free" in txt) OUTPUT: True • Print only if "free" is present: txt = "The best things in life are free!" if "free" in txt: print("Yes, 'free' is present.") OUTPUT: Yes, 'free' is present.
  • 13. Check if NOT • To check if a certain phrase or character is NOT present in a string, we can use the keyword not in. • Check if "expensive" is NOT present in the following text: txt = "The best things in life are free!" print("expensive" not in txt) OUTPUT: True
  • 14. • print only if "expensive" is NOT present: txt = "The best things in life are free!" if "expensive" not in txt: print("No, 'expensive' is NOT present.")
  • 15. Slicing Strings Slicing • 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. • Get the characters from position 2 to position 5 (not included): b = "Hello, World!" print(b[2:5]) Note: The first character has index 0. OUTPUT: llo
  • 16. Slice From the Start • By leaving out the start index, the range will start at the first character: • Get the characters from the start to position 5 (not included): b = "Hello, World!" print(b[:5])
  • 17. Slice To the End • By leaving out the end index, the range will go to the end: • Get the characters from position 2, and all the way to the end: b = "Hello, World!" print(b[2:])
  • 18. Negative Indexing • Use negative indexes to start the slice from the end of the string: Get the characters: • From: "o" in "World!" (position -5) • To, but not included: "d" in "World!" (position -2): b = "Hello, World!" print(b[-5:-2]) OUTPUT: orl
  • 19. Modify Strings • Python has a set of built-in methods that you can use on strings. UPPER CASE • The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) Output: HELLO, WORLD! LOWER CASE The lower() method returns the string in lower case: a = "Hello, World!" print(a.lower()) Output: hello, world!
  • 20. 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!
  • 21. Replace String • The replace() method replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J")) Output: Jello, World!
  • 22. Split String • The split() method returns a list where the text between the specified separator becomes the list items. • The split() method splits the string into substrings if it finds instances of the separator: a ="Hello, World!" print(a.split(",")) OUTPUT: ['Hello', ' World!']
  • 23. String Concatenation • To concatenate, or combine, two strings you can use the + operator. • Merge variable a with variable b into variable c: a = "Hello" b = "World" c = a + b print(c) Output: HelloWorld
  • 24. String Concatenation • To add a space between them, add a " ": a = "Hello" b = "World" c = a + " " + b print(c)
  • 25. String Format • In Python we cannot combine strings and numbers like this: age = 36 txt = "My name is John, I am " + age print(txt) But we can combine strings and numbers by using the format() method! The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are.
  • 26. String Format • Use the format() method to insert numbers into strings: age = 36 txt = "My name is John, and I am {}" print(txt.format(age)) Output: My name is John, and I am 36
  • 27. String Format The format() method takes unlimited number of arguments, and are placed into the respective placeholders: quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) OUTPUT: I want 3 pieces of item 567 for 49.95 dollars.
  • 28. String Format • You can use index numbers {0} to be sure the arguments are placed in the correct placeholders: quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) Output: I want to pay 49.95 dollars for 3 pieces of item 567
  • 29. capitalize() Method • Upper case the first letter in this sentence: txt = "hello, and welcome to my world." x = txt.capitalize() print (x) OUTPUT: Hello, and welcome to my world.