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

PPTX
Python Strings.pptx
PPTX
Day5 String python language for btech.pptx
PDF
Strings in Python
PDF
Python data handling
PDF
stringsinpython-181122100212.pdf
PPTX
Strings cprogramminglanguagedsasheet.pptx
PPTX
Python Strings and its Featues Explained in Detail .pptx
PPTX
Tokens in php (php: Hypertext Preprocessor).pptx
Python Strings.pptx
Day5 String python language for btech.pptx
Strings in Python
Python data handling
stringsinpython-181122100212.pdf
Strings cprogramminglanguagedsasheet.pptx
Python Strings and its Featues Explained in Detail .pptx
Tokens in php (php: Hypertext Preprocessor).pptx

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

PDF
String class and function for b.tech iii year students
PDF
C string _updated_Somesh_SSTC_ Bhilai_CG
PPT
M C6java7
PPTX
Learn python in 20 minutes
PDF
Python Strings Methods
PDF
05 c++-strings
PDF
0-Slot21-22-Strings.pdf
PPTX
Data Type In Python.pptx
PPTX
varthini python .pptx
PDF
String notes
PPTX
Python Strings.pptx
PPTX
Computer programming 2 Lesson 12
PPTX
Lecture 15_Strings and Dynamic Memory Allocation.pptx
PPTX
13 Strings and Text Processing
PPTX
Python Workshop - Learn Python the Hard Way
PPTX
Introduction to python programming ( part-3 )
PPTX
1-Object and Data Structures.pptx
PDF
Strings in java
PPTX
Different uses of String in Python.pptx
PPTX
java program in Abstract class . pptx
String class and function for b.tech iii year students
C string _updated_Somesh_SSTC_ Bhilai_CG
M C6java7
Learn python in 20 minutes
Python Strings Methods
05 c++-strings
0-Slot21-22-Strings.pdf
Data Type In Python.pptx
varthini python .pptx
String notes
Python Strings.pptx
Computer programming 2 Lesson 12
Lecture 15_Strings and Dynamic Memory Allocation.pptx
13 Strings and Text Processing
Python Workshop - Learn Python the Hard Way
Introduction to python programming ( part-3 )
1-Object and Data Structures.pptx
Strings in java
Different uses of String in Python.pptx
java program in Abstract class . pptx
Ad

Recently uploaded (20)

PPT
LEC Synthetic Biology and its application.ppt
PPTX
gene cloning powerpoint for general biology 2
PPTX
Preformulation.pptx Preformulation studies-Including all parameter
PPT
Enhancing Laboratory Quality Through ISO 15189 Compliance
PPTX
2currentelectricity1-201006102815 (1).pptx
PDF
Packaging materials of fruits and vegetables
PPTX
endocrine - management of adrenal incidentaloma.pptx
PDF
Worlds Next Door: A Candidate Giant Planet Imaged in the Habitable Zone of ↵ ...
PDF
CuO Nps photocatalysts 15156456551564161
PDF
Cosmology using numerical relativity - what hapenned before big bang?
PDF
GROUP 2 ORIGINAL PPT. pdf Hhfiwhwifhww0ojuwoadwsfjofjwsofjw
PDF
Worlds Next Door: A Candidate Giant Planet Imaged in the Habitable Zone of ↵ ...
PDF
Is Earendel a Star Cluster?: Metal-poor Globular Cluster Progenitors at z ∼ 6
PDF
BET Eukaryotic signal Transduction BET Eukaryotic signal Transduction.pdf
PPTX
Understanding the Circulatory System……..
PPT
THE CELL THEORY AND ITS FUNDAMENTALS AND USE
PPTX
TORCH INFECTIONS in pregnancy with toxoplasma
PDF
Communicating Health Policies to Diverse Populations (www.kiu.ac.ug)
PDF
Integrative Oncology: Merging Conventional and Alternative Approaches (www.k...
PPTX
Platelet disorders - thrombocytopenia.pptx
LEC Synthetic Biology and its application.ppt
gene cloning powerpoint for general biology 2
Preformulation.pptx Preformulation studies-Including all parameter
Enhancing Laboratory Quality Through ISO 15189 Compliance
2currentelectricity1-201006102815 (1).pptx
Packaging materials of fruits and vegetables
endocrine - management of adrenal incidentaloma.pptx
Worlds Next Door: A Candidate Giant Planet Imaged in the Habitable Zone of ↵ ...
CuO Nps photocatalysts 15156456551564161
Cosmology using numerical relativity - what hapenned before big bang?
GROUP 2 ORIGINAL PPT. pdf Hhfiwhwifhww0ojuwoadwsfjofjwsofjw
Worlds Next Door: A Candidate Giant Planet Imaged in the Habitable Zone of ↵ ...
Is Earendel a Star Cluster?: Metal-poor Globular Cluster Progenitors at z ∼ 6
BET Eukaryotic signal Transduction BET Eukaryotic signal Transduction.pdf
Understanding the Circulatory System……..
THE CELL THEORY AND ITS FUNDAMENTALS AND USE
TORCH INFECTIONS in pregnancy with toxoplasma
Communicating Health Policies to Diverse Populations (www.kiu.ac.ug)
Integrative Oncology: Merging Conventional and Alternative Approaches (www.k...
Platelet disorders - thrombocytopenia.pptx
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