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

Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsPallavi Parmar
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxMichaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxRugvedSathawane
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use CasesTechSoup
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 

Recently uploaded (20)

Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell Tolls
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxMichaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 

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.