SlideShare a Scribd company logo
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

PPTX
Python Strings.pptx
PPTX
UNIT 4 python.pptx
PPT
PPS_Unit 4.ppt
PDF
Python Objects and Data Structure Basics
PPTX
Review old Pygame made using python programming.pptx
PPTX
varthini python .pptx
PDF
Python revision tour II
PPT
String and string manipulation
Python Strings.pptx
UNIT 4 python.pptx
PPS_Unit 4.ppt
Python Objects and Data Structure Basics
Review old Pygame made using python programming.pptx
varthini python .pptx
Python revision tour II
String and string manipulation

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

PDF
0-Slot21-22-Strings.pdf
PPTX
Review 2Pygame made using python programming
PDF
14-Strings-In-Python strings with oops .pdf
PPTX
Strings cprogramminglanguagedsasheet.pptx
PDF
stringsinpython-181122100212.pdf
PPTX
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
PPTX
Python ppt
PPSX
String and string manipulation x
PDF
Strings brief introduction in python.pdf
PPTX
INTRODUCTION TO PYTHON.pptx
PPTX
STRINGS_IN_PYTHON 9-12 (1).pptx
PPTX
Engineering CS 5th Sem Python Module -2.pptx
PPTX
Python Strings and strings types with Examples
PPTX
Python strings presentation
PPT
Chapter05.ppt
PPTX
Strings in c++
PPTX
STRINGS IN PYTHON
PDF
strings in python (presentation for DSA)
PPTX
fundamentals of c programming_String.pptx
PPTX
Python_Unit_III.pptx
0-Slot21-22-Strings.pdf
Review 2Pygame made using python programming
14-Strings-In-Python strings with oops .pdf
Strings cprogramminglanguagedsasheet.pptx
stringsinpython-181122100212.pdf
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
Python ppt
String and string manipulation x
Strings brief introduction in python.pdf
INTRODUCTION TO PYTHON.pptx
STRINGS_IN_PYTHON 9-12 (1).pptx
Engineering CS 5th Sem Python Module -2.pptx
Python Strings and strings types with Examples
Python strings presentation
Chapter05.ppt
Strings in c++
STRINGS IN PYTHON
strings in python (presentation for DSA)
fundamentals of c programming_String.pptx
Python_Unit_III.pptx
Ad

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
Final Presentation General Medicine 03-08-2024.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
A systematic review of self-coping strategies used by university students to ...
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Module 4: Burden of Disease Tutorial Slides S2 2025
Complications of Minimal Access Surgery at WLH
Orientation - ARALprogram of Deped to the Parents.pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Ad

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.