Python Methods
Python Methods
collection characters
Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
Example
print("Hello")
print('Hello')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
Example
Check if "free" is present in the following text:
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use
the keyword not in.
Example
Check if "expensive" is NOT present in the following text:
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.
Example:
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Example
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:
Example
Get the characters:
b = "Hello, World!"
print(b[-5:-2])
Python - Modify Strings:
Python has a set of built-in methods that you can use on strings.
Upper Case
ExampleGet your own Python Server
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you
want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c = a + b
print(c)
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:
Example:
age = 36
txt = "My name is John, I am " + age
print(txt)
Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)
Example
Perform a math operation in the placeholder, and return the result:
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where i
index() Searches the string for a specified value and returns the position of where i
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of whe
rindex() Searches the string for a specified value and returns the last position of whe
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Python Set Methods:
Syntax:set.add(elmnt)
Example:
fruits.add("orange")
print(fruits)
clear() Removes all the elements from the set
syntax: set.clear()
fruits.clear()
print(fruits)
syntax:set.copy()
x = fruits.copy()
print(x)
or more sets
z = x.difference(y)
print(z)
difference_update() -= Removes the items in this set that are also included in
specified set
discard() Remove the specified item
syntax: set.discard(value)
fruits.discard("banana")
print(fruits)
other sets
z = x.intersection(y)
print(z)
intersection_update() &= Removes the items in this set that are not present in
set(s)
x.intersection_update(y)
print(x)
z = x.isdisjoint(y)
print(z)
issubset() < Returns whether another set contains this set or not
=
Syntax: set.issubset(set1)
z = x.issubset(y)
print(z)
issuperset() > Returns whether this set contains another set or not
=
Syntax: set.issuperset(set)
z = x.issuperset(y)
print(z)
fruits.pop()
print(fruits)
Syntax: set.remove(item)
fruits.remove("banana")
print(fruits)
z = x.union(y)
print(z)
update() |= Update the set with the union of this set and others
Example:
x.update(y)
print(x)
Syntax: dictionary.clear()
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
thisdict = dict.fromkeys(x, y)
print(thisdict)
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x)
items() Returns a list containing a tuple for each key value pair
Syntax: dictionary.items()
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
Syntax: dictionary.keys()
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
print(car)
Syntax: dictionary.popitem()
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)
setdefault() Returns the value of the specified key. If the key does not exist: insert the key
specified value
Syntax: dictionary.update(iterable)
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
Syntax: dictionary.values()
Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)
Exmple2: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.values()
car["year"] = 2018
print(x)
Python Functions:
A function is a block of code which only runs when it is called.
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
❮ PreviousNext ❯
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
This way the function will receive a dictionary of arguments, and can access the
items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Positional-Only Arguments
You can specify that a function can have ONLY positional arguments, or ONLY
keyword arguments.
To specify that a function can have only positional arguments, add , / after the
arguments:
Example
def my_function(x, /):
print(x)
my_function(3)
Without the , / you are actually allowed to use keyword arguments even if the
function expects positional arguments:
Example
def my_function(x):
print(x)
my_function(x = 3)
But when adding the , / you will get an error if you try to send a keyword
argument:
Example
def my_function(x, /):
print(x)
my_function(x = 3)
Keyword-Only Arguments
To specify that a function can have only keyword arguments, add *, before the
arguments:
Example
def my_function(*, x):
print(x)
my_function(x = 3)
Without the *, you are allowed to use positionale arguments even if the
function expects keyword arguments:
Example
def my_function(x):
print(x)
my_function(3)
But with the *, you will get an error if you try to send a positional argument:
Example
def my_function(*, x):
print(x)
my_function(3)
Example
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)
Recursion
In Python, a recursive function is defined like any other function, but it
includes a call to itself.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))