in operator (membership operator)
- In Python in is a keyword.
- The in and not in operators test for membership.
- We can use them with strings to test if one string is a substring of another. This operation is case-sensitive.
1s = "Pineapple"23print("app" in s) # True4print("pine" in s) # False56print("x" not in s) # True7print("P" not in s) # False
Try the problem “Remove Duplicates” on Ed Lessons.
Try the problem “Benchpress” on Ed Lessons.
String methods
A method is similar to a function except that a method is always called on an object:
object.method_name(argument1, argument2, …)
str type has several methods that we can call on a string object:
1print("hello".upper()) # calling method upper() on the string "hello"2# HELLO34message = "hello"5print(message.upper()) # using variable that refers to string6# HELLO78message = 109print(message.upper()) # upper() only available for str objects10# AttributeError: 'int' object has no attribute 'upper'
Useful string methods
1s = "Luke, I am your father"23# s.lower() : returns a copy of s, but with all lower case letters.4print(s.lower())5# luke, i am your father67# s.upper() : returns a copy of s, but with all upper case letters.8print(s.upper())9# LUKE, I AM YOUR FATHER
1s = "Luke, I am your father"2# s.replace(old, new) : returns a copy of s with all occurrences of3# the substring old replaced by new.4print(s.replace("am", "am not"))5# Luke, I am not your father67# replace space with empty string8print(s.replace(" ", ""))9# Luke,Iamyourfather
1s = "banana"2# s.count(c) : returns the number of non-overlapping3# occurrences of substring c in s.4print(s.count("na"))5# 267# s.find(c) : returns the index where the substring begins in s begins.8# If c is not a substring of s, then -1 is returned.9print(s.find("an"))10# 11112print(s.find("naa"))13# -1
1x = 12y = 2.53z = 3.144name = "Reza"56# fmt.format(a1, a2, ...):7# returns a string where the placeholders {} in format string fmt8# are replaced by args a1, a2, etc.910print("x = {}, y = {}".format(x, y))11# x = 1, y = 2.51213print("Point: ({}, {}, {})".format(x, y, z))14# Point: (1, 2.5, 3.14)1516print("Welcome {}!".format(name))17# Welcome Reza!
Formatted Strings
1x = 12y = 2.53z = 3.144name = "Reza"56print(f"x = {x}, y = {y}")7# x = 1, y = 2.589print(f"Point: ({x}, {y}, {z})")10# Point: (1, 2.5, 3.14)1112print(f"Welcome {name}!")13# Welcome Reza!
Example
In just one expression, compare if two strings s1 and s2 are equal in a case-insensitive manner.
1s1 = "Hello Everyone"2s2 = "hello everyone"34is_equal = s1.upper() == s2.upper()56# OR7# is_equal = s1.lower() == s2.lower()89print(is_equal) # prints True
break statement
break statement can be used to terminate a loop before it normally ends.
After a break statement is executed, no other code inside the loop is executed.
1for i in range(10):2 if i > 5:3 break4 print(i)56print("Bye!")
0 1 2 3 4 5 Bye!
Write a function is_prime that takes an integer as argument and returns True if the number is prime, otherwise returns False. To check if a number n is prime:
- Assume n is prime
- Divide n by each number i from 2 to n-1
- if n is divisible by any i then n cannot be not prime
In other words, if n is not divisible by all i’s then n is prime.
1def is_prime(num):2 prime = True34 if num < 2:5 prime = False6 else:7 for i in range(2, num):8 if num % i == 0:9 prime = False10 break1112 return prime1314print(is_prime(7)) # True15print(is_prime(21)) # False
1password = input("Enter password: ")23while password != "abcd1234":4 print("Incorrect password, try again!")5 password = input("Enter password: ")67print("Login successful!")
Change above program so that it keeps asking email and password until both are correct.
Password comparison must be case-sensitive, while email comparison should be case-insensitive.
For comparison, just choose any email, password that you like.
1email = input("Enter email: ")2password = input("Enter password: ")34while email.lower() != "abcd@gmail.com" or password != "1234":5 print("Incorrect email or password, try again!")67 email = input("Enter email: ")8 password = input("Enter password: ")910# If we reach this line it means both email and password were correct11print("Login successful!")
Using break in a while loop
We can simplify the login example using a break statement:
1while True:2 email = input("Enter email: ")3 password = input("Enter password: ")4 if email.lower() == "abcd@gmail.com" and password == "1234":5 break6 print("Incorrect email or password, try again!")78print("Login successful!")
continue statement
continue statement is useful to skip some steps in a loop.
After a continue statement is executed, code that follows the statement is skipped and execution continues from the next step of the loop.
1for i in range(1, 50):2 if i % 2 == 0 or i % 3 == 0:3 continue4 print(i)
1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49