Strings 2 (2 hours)

Class Recording
Lecture Notes
Old Script

Content

  1. Various String methods.
  2. Concept of Mutability and Immutability

Meanwhile when people are joining (5-7 mins)

  • Instructor's welcome.
  • Breaking ice with students.
  • Casual conversation to bond.

title: Quiz-1
description:
duration: 60
card_type: quiz_card

Question

What will be the output of the following code?

message = "Hello World!" i = 0 while i < len(message): if i % 2 == 0: print(message[i], end = "") i += 1

Choices

  • HloWrd
  • Hlo ol
  • eolWrd
  • el or

title: String Methods
description:
duration: 2400
card_type: cue_card

String Methods

.split() method

  • The str.split() function converts a string into a list of characters based on a splitting criteria.

Code:

"4 5 6 7 8 9".split()

Output:

['4', '5', '6', '7', '8', '9']

Code:

"This_is_a_underscore_separated_string".split("_")

Output:

['This', 'is', 'a', 'underscore', 'separated', 'string']

.join() method

  • Opposite of splitting is joining.
  • We can use str.join() to do so.

Code:

random = "This_is_a_underscore_separated_string".split("_") " ".join(random)

Output:

'This is a underscore separated string'

Code:

"-".join(random)

Output:

'This-is-a-underscore-separated-string'
  • While providing an iterable to .join() you need to make sure that the contents of that iterable only contain strings. Else it will throw an error.

Code:

# Error a = ["random", 102, 282, "string"] " ".join(a)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-6c67814fded6> in <module>
      1 a = ["random", 102, 282, "string"]
----> 2 " ".join(a)

TypeError: sequence item 1: expected str instance, int found

str() function

  • We can use str() function to convert numbers to string.

Code:

str(45)

Output:

'45'

.find() method

  • The .find() method can be used to find a substring inside a string that we can call it on.
  • This function returns the starting index of the first occourance of the substring that we are trying to find inside the string.

Code:

"this is a random string".find("is")

Output:

2
  • Returns -1 if the substring is not present.

Code:

"this is a random string".find("adadsaf")

Output:

-1

.replace() method

  • The method .replace() can be used to replace a substring from the original string with the input we provide.
  • This method takes in two arguments, first the substring from the original string and second the string we want to replace it with.
  • It replaces the string we provide and returns a new string.

Code:

random = "This is a random string that I have created" # The orginal string is not updated. random.replace("random", "SUPER RANDOM")

Output:

'This is a SUPER RANDOM string that I have created'

.count() method

  • The method .count() can be used to count the number of occourances of a substring we provide inside a particular string.

Code:

random = "This is a random string that I have created" random.count("a")

Output:

5

Code:

random = "This is a random string that I have created random random random" random.count("random")

Output:

4

title: Question-1
description:
duration: 480
card_type: cue_card

  • Take a string as input.
  • Convert the string to lowercase without using any inbuilt function.

Code:

def custom_lower(s): result = "" for i in s: if ord(i) >= 65 and ord(i) <= 90: order = ord(i) order = order + 32 result = result + chr(order) else: result = result + i return result custom_lower("This is A stRIng")

Output:

'this is a string'

title: Quiz-2
description:
duration: 60
card_type: quiz_card

Question

What will be the output of the following code?

message = "Hello World!" print(message.lower())

Choices

  • HELLO WORLD!
  • hello world!
  • hELLO wORLD!
  • Hello World!

title: Quiz-3
description:
duration: 60
card_type: quiz_card

Question

What will be the output of the following code?

message = "Hello World!" print(message.replace("o", "e"))

Choices

  • Helle Welle
  • Helle Welle!
  • Helle Werld!
  • Hllo Wrld!

title: Some more methods
description:
duration: 1800
card_type: cue_card

Some more methods -

.isdigit()

  • .isdigit() returns True a character inside a string is a digit.
  • This method works only for integers.

Code:

"6".isdigit()

Output:

True

Code:

"a".isdigit()

Output:

False

Code:

"aasda231321".isdigit()

Output:

False

Code:

"124143222".isdigit()

Output:

True

.isalpha()

  • isalpha() returns True if a certain string only contains alphabets

Code:

"aasda231321".isalpha()

Output:

False

Code:

"a".isalpha()

Output:

True

Code:

"abc".isalpha()

Output:

True

.isupper() and .islower()

Code:

"A".isupper()

Output:

True

Code:

"a".isupper()

Output:

False

Code:

"a".islower()

Output:

True

Code:

"A".islower()

Output:

False

.isspace()

  • Returns True if there is a space in the string.

Code:

"abc".isspace()

Output:

False

Code:

" ".isspace()

Output:

True

title: Question-2
description:
duration: 400
card_type: cue_card

  • Take a string as input.
  • Replace all the space with underscore.

Code:

string = "this is a random string" # 1 def change_to_underscore(s): result = "" for i in s: if i.isspace(): result = result + "_" else: result = result + i return result change_to_underscore(string)

Output:

'this_is_a_random_string'

Code:

# 2 string.replace(" ", "_")

Output:

this_is_a_random_string

title: Quiz-4
description:
duration: 60
card_type: quiz_card

Question

What will be the output of the following code?

message = "Not Hello World!" print(message.startswith("Hello"))

Choices

  • True
  • False
  • None
  • Error

title: Quiz-5
description:
duration: 60
card_type: quiz_card

Question

What will be the output of the following code?

message = "Hello World!" print(message.find("o"))

Choices

  • 8
  • 7
  • 4
  • -1

title: Glossary of string methods
description:
duration: 90
card_type: cue_card

Glossary of string methods -

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

title: Mutability and Immutability
description:
duration: 900
card_type: cue_card

Mutability and Immutability

Mutable: whose value can change.
Immutable: whose value can't change.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Code:

a = 3 a

Output:

3

Code:

a = 4 a

Output:

4

It seems that integers are mutable but NO. originally in python we are just changing the memory reference of a to point to 4 instead of changing its value to 4.

Only 3 data types in python are mutable

  • list
  • sets
  • dictionaries

Other data types such as strings and tuples(you are going to learn in upcoming lectures) are immutable.

id() function in python gives the memory address of the variable where it is stored

Code:

id(a)

Output:

140424322138448

Code:

a = 6 id(a) # it can be seen that memory address is change hence now a is pointing to somewhere else in memory

Output:

140424322138512

Code:

my_list =["Python", "C++", "Java"] id(my_list)

Output:

140423632449408

Code:

my_list.append("HTML") my_list[0] = "Python 3.5" print(my_list) print(id(my_list))

Output:

['Python 3.5', 'C++', 'Java', 'HTML', 'HTML']
140423632449408

As lists are mutable, we can see that the same list created in the first cell is modified and the values are changed in the same memory location.

Code:

my_string = "Scaled" my_string[5] = "r" # Trying to change the character in the last index print(my_string)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-5b191cb176fc> in <cell line: 2>()
      1 my_string  = "Scaled"
----> 2 my_string[5] = "r"  # Trying to change the character in the last index
      3 print(my_string)

TypeError: 'str' object does not support item assignment
  • We receive an error as strings are immutable and we cannot change the value in place.
  • We can instead assign a new value to the same variable, which leads to the creation of a different memory space

Code:

print(id(my_string))

Output:

140423625872112

Code:

my_string = "Scaler" print(id(my_string))

Output:

140423066082608