0% found this document useful (0 votes)
2 views

Python Methods

The document provides an overview of Python strings, including how to create, manipulate, and access them. It covers string methods, string formatting, and the differences between strings and other data types like sets and dictionaries. Additionally, it explains how to define and call functions in Python, including handling arguments and using arbitrary arguments.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Methods

The document provides an overview of Python strings, including how to create, manipulate, and access them. It covers string methods, string formatting, and the differences between strings and other data types like sets and dictionaries. Additionally, it explains how to define and call functions in Python, including handling arguments and using arbitrary arguments.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Python Strings:

collection characters
Strings
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:

Example
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:

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)

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.

Example
Get the character at position 1 (remember that the first character has the
position 0):

a = "Hello, World!"
print(a[1])

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with
a for loop.

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:

txt = "The best things in life are free!"


print("free" in txt)

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:

txt = "The best things in life are free!"


print("expensive" not in txt)

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])

Slice From the Start


By leaving out the start index, the range will start at the first character:

Example
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:

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:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

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:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

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.

ExampleGet your own Python Server


Merge variable a with variable b into variable c:

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)

Placeholders and Modifiers


A placeholder can contain variables, operations, functions, and modifiers to
format the value.

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:

txt = f"The price is {20 * 59} dollars"


print(txt)

Python - String Methods:


Method Description

capitalize() Converts the first character to upper case


casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where i

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where i

isalnum() Returns True if all characters in the string are alphanumeric


isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

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

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

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

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning
Python Set Methods:

add() Adds an element to the set

Syntax:set.add(elmnt)

Example:

fruits = {"apple", "banana", "cherry"}

fruits.add("orange")

print(fruits)
clear() Removes all the elements from the set

syntax: set.clear()

example: fruits = {"apple", "banana", "cherry

fruits.clear()

print(fruits)

copy() Returns a copy of the set

syntax:set.copy()

example: fruits = {"apple", "banana", "cherry

x = fruits.copy()

print(x)

difference() - Returns a set containing the difference between two

or more sets

syntax: set.difference(set1, set2 ... etc.)

example: x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

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)

Example: fruits = {"apple", "banana", "cherry

fruits.discard("banana")

print(fruits)

intersection() & Returns a set, that is the intersection of two

other sets

syntax: set.intersection(set1, set2 ... etc.)

example: x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z)

intersection_update() &= Removes the items in this set that are not present in
set(s)

syntax: set.intersection_update(set1, set2 ...

Example: x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

isdisjoint() Returns whether two sets have a intersection or not


Syntax: set.isdisjoint(set)

Example: x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "facebook"}

z = x.isdisjoint(y)

print(z)

issubset() < Returns whether another set contains this set or not
=
Syntax: set.issubset(set1)

Example: x = {"a", "b", "c"}


y = {"f", "e", "d", "c", "b", "a"}

z = x.issubset(y)

print(z)

issuperset() > Returns whether this set contains another set or not
=
Syntax: set.issuperset(set)

Example: x = {"f", "e", "d", "c", "b", "a"}


y = {"a", "b", "c"}

z = x.issuperset(y)

print(z)

> Returns whether all items in other, specified set(s) is


set

pop() Removes an element from the set


Syntax: set.pop()

Example: fruits = {"apple", "banana", "cherry

fruits.pop()

print(fruits)

remove() Removes the specified element

Syntax: set.remove(item)

Example: fruits = {"apple", "banana", "cherry

fruits.remove("banana")

print(fruits)

symmetric_difference() ^ Returns a set with the symmetric differences of two s

symmetric_difference_update() ^ Inserts the symmetric differences from this set and an


=

union() | Return a set containing the union of sets

Syntax: set.union(set1, set2...)

Example: x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

z = x.union(y)

print(z)
update() |= Update the set with the union of this set and others

Syntax: set.update(set1, set2 ...)

Example:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.update(y)

print(x)

Python Dictionary Methods:


Method Description

clear() Removes all the elements from the dictionary

Syntax: dictionary.clear()

Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.clear()

print(car)

copy() Returns a copy of the dictionary


Syntax: dictionary.copy()

Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.copy()

print(x)

fromkeys() Returns a dictionary with the specified keys and value

Syntax: dict.fromkeys(keys, value)

Example: x = ('key1', 'key2', 'key3')


y = 0

thisdict = dict.fromkeys(x, y)

print(thisdict)

get() Returns the value of the specified key

Syntax: dictionary.get(keyname, value)

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)

keys() Returns a list containing the dictionary's keys

Syntax: dictionary.keys()

Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x)

pop() Removes the element with the specified key

Syntax: dictionary.pop(keyname, defaultvalue)

Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.pop("model")
print(car)

popitem() Removes the last inserted key-value pair

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

update() Updates the dictionary with the specified key-value pairs

Syntax: dictionary.update(iterable)

Example: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.update({"color": "White"})

print(car)

values() Returns a list of all the values in the dictionary

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.

You can pass data, known as parameters, into a function.

A function can return data as a result.


Creating a Function
In Python a function is defined using the def keyword:

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")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition

❮ 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])

my_function("Emil", "Tobias", "Linus")

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments,


**kwargs
If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.

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"])

my_function(fname = "Tobias", lname = "Refsnes")

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

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)

fruits = ["apple", "banana", "cherry"]

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)

Combine Positional-Only and Keyword-


Only
You can combine the two argument types in the same function.

Any argument before the / , are positional-only, and any


argument after the *, are keyword-only.

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))

You might also like