Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!") #This is a comment
print(type(x))
x = 5
y = "John"
x, y, z = "Orange", "Banana", "Cherry"
x = y = z = "Orange"
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
global x
import random print(random.randrange(1, 10))
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
a = "Hello"
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
a = "Hello, World!"
print(a[1])
for x in "banana":
print(x)
len(a)
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[:5])
b = "Hello, World!"
print(b[2:])
b = "Hello, World!"
print(b[-5:-2])
a.upper()
a.lower()
print(a.strip()) # returns "Hello, World!"
print(a.replace("H", "J"))
print(a.split(",")) # returns ['Hello', ' World!']
c = "Hello" + "World"
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Code | Result | |
---|---|---|
\' | Single Quote | |
\\ | Backslash | |
\n | New Line | |
\r | Carriage Return | |
\t | Tab | |
\b | Backspace | |
\f | Form Feed | |
\ooo | Octal value | |
\xhh | Hex value |
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 it was found |
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 it was found |
isalnum() | Returns True if all characters in the string are alphanumeric |
isalpha() | Returns True if all characters in the string are in the alphabet |
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 where it was found |
rindex() | Searches the string for a specified value and returns the last position of where it was found |
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 |
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Operator | Name | Example |
---|---|---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus | x % y |
** | Exponentiation | x ** y |
// | Floor division | x // y |
Operator | Example | Same As |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
//= | x //= 3 | x = x // 3 |
**= | x **= 3 | x = x ** 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Operator | Name | Example |
---|---|---|
== | Equal | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Operator | Description | Example |
---|---|---|
and | Returns True if both statements are true | x < 5 and x < 10 |
or | Returns True if one of the statements is true | x < 5 or x < 4 |
not | Reverse the result, returns False if the result is true | not(x < 5 and x < 10) |
Operator | Description | Example |
---|---|---|
is | Returns True if both variables are the same object | x is y |
is not | Returns True if both variables are not the same object | x is not y |
Operator | Description | Example |
---|---|---|
in | Returns True if a sequence with the specified value is present in the object | x in y |
not in | Returns True if a sequence with the specified value is not present in the object | x not in y |
Operator | Name | Description |
---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 |
| | OR | Sets each bit to 1 if one of two bits is 1 |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 |
~ | NOT | Inverts all the bits |
<< | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |
>> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
thislist = ["apple", "banana", "cherry"]
print(thislist)
len(thislist)
type(mylist)
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon") #Insert "watermelon" as the third item
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical) #To append elements from another list to the current list
thislist.remove("banana")
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
del thislist
thislist.clear()
for x in thislist:
print(x)
for i in range(len(thislist)):
print(thislist[i])
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []for x in fruits:
if "a" in x:
newlist.append(x)
thislist.reverse()
def myfunc(n):
return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
thislist.sort()
thislist.sort(reverse = True)
mylist = thislist.copy()
mylist = list(thislist)
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
Method | Description |
---|---|
append() | Adds an element at the end of the list |
clear() | Removes all the elements from the list |
copy() | Returns a copy of the list |
count() | Returns the number of elements with the specified value |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
pop() | Removes the element at the specified position |
remove() | Removes the item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |
thistuple = ("apple", "banana", "cherry")
print(thistuple)
len(thistuple)
thistuple = ("apple",)
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += yprint(thistuple) #Insert "watermelon" as the third item
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
fruits = ("apple", "banana", "cherry","clory")(green, yellow, red) = fruitsprint(green)
print(yellow)
print(red)
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)tuple3 = tuple1 + tuple2
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
thisset = {"apple", "banana", "cherry"}
print(thisset)
len(thislist)
type(mylist)
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
thisset = {"apple", "banana", "cherry"}for x in thisset:
print(x)
thisset = {"apple", "banana", "cherry"}thisset.add("orange")
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
thisset = {"apple", "banana", "cherry"}thisset.discard("banana")
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
thisset = {"apple", "banana", "cherry"}
thisset.clear()
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
thisset = {"apple", "banana", "cherry"}for x in thisset:
print(x)
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}x.intersection_update(y)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all the elements from the set |
copy() | Returns a copy of the set |
difference() | Returns a set containing the difference between two or more sets |
difference_update() | Removes the items in this set that are also included in another, specified set |
discard() | Remove the specified item |
intersection() | Returns a set, that is the intersection of two other sets |
intersection_update() | Removes the items in this set that are not present in other, specified set(s) |
isdisjoint() | Returns whether two sets have a intersection or not |
issubset() | Returns whether another set contains this set or not |
issuperset() | Returns whether this set contains another set or not |
pop() | Removes an element from the set |
remove() | Removes the specified element |
symmetric_difference() | Returns a set with the symmetric differences of two sets |
symmetric_difference_update() | inserts the symmetric differences from this set and another |
union() | Return a set containing the union of sets |
update() | Update the set with the union of this set and others |
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
len(thislist)
type(mylist)
thisdict = dict(name = "John", age = 36, country = "Norway")
x = thisdict.get("model")
x = thisdict.keys()
x = thisdict.values()
x = thisdict.items()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
for x in thisdict:
print(x)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary |
copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and value |
get() | Returns the value of the specified key |
items() | Returns a list containing a tuple for each key value pair |
keys() | Returns a list containing the dictionary's keys |
pop() | Removes the element with the specified key |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates the dictionary with the specified key-value pairs |
values() | Returns a list of all the values in the dictionary |
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a = 33
b = 200
if b > a:
pass
i = 1
while i < 6:
print(i)
i += 1
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in range(2,6):
print(x)
def my_function():
print("Hello from a function")
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
lambda arguments : expression
def myfunc(n):
return lambda a : a * n
cars = ["Ford", "Volvo", "BMW"]
Method | Description |
---|---|
append() | Adds an element at the end of the list |
clear() | Removes all the elements from the list |
copy() | Returns a copy of the list |
count() | Returns the number of elements with the specified value |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
pop() | Removes the element at the specified position |
remove() | Removes the first item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname) }
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
for x in mytuple:
print(x)
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
def myfunc():
global x
x = 300
myfunc()
print(x)
import mymodule
import mymodule as mx
import datetime
x = datetime.datetime.now()
print(x)
Directive | Description | Example | |
---|---|---|---|
%a | Weekday, short version | Wed | |
%A | Weekday, full version | Wednesday | |
%w | Weekday as a number 0-6, 0 is Sunday | 3 | |
%d | Day of month 01-31 | 31 | |
%b | Month name, short version | Dec | |
%B | Month name, full version | December | |
%m | Month as a number 01-12 | 12 | |
%y | Year, short version, without century | 18 | |
%Y | Year, full version | 2018 | |
%H | Hour 00-23 | 17 | |
%I | Hour 00-12 | 05 | |
%p | AM/PM | PM | |
%M | Minute 00-59 | 41 | |
%S | Second 00-59 | 08 | |
%f | Microsecond 000000-999999 | 548513 | |
%z | UTC offset | +0100 | |
%Z | Timezone | CST | |
%j | Day number of year 001-366 | 365 | |
%U | Week number of year, Sunday as the first day of week, 00-53 | 52 | |
%W | Week number of year, Monday as the first day of week, 00-53 | 52 | |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 | |
%C | Century | 20 | |
%x | Local version of date | 12/31/18 | |
%X | Local version of time | 17:41:00 | |
%% | A % character | % | |
%G | ISO 8601 year | 2018 | |
%u | ISO 8601 weekday (1-7) | 1 | |
%V | ISO 8601 weeknumber (01-53) | 01 |
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
Method | Description |
---|---|
math.acos() | Returns the arc cosine of a number |
math.acosh() | Returns the inverse hyperbolic cosine of a number |
math.asin() | Returns the arc sine of a number |
math.asinh() | Returns the inverse hyperbolic sine of a number |
math.atan() | Returns the arc tangent of a number in radians |
math.atan2() | Returns the arc tangent of y/x in radians |
math.atanh() | Returns the inverse hyperbolic tangent of a number |
math.ceil() | Rounds a number up to the nearest integer |
math.comb() | Returns the number of ways to choose k items from n items without repetition and order |
math.copysign() | Returns a float consisting of the value of the first parameter and the sign of the second parameter |
math.cos() | Returns the cosine of a number |
math.cosh() | Returns the hyperbolic cosine of a number |
math.degrees() | Converts an angle from radians to degrees |
math.dist() | Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point |
math.erf() | Returns the error function of a number |
math.erfc() | Returns the complementary error function of a number |
math.exp() | Returns E raised to the power of x |
math.expm1() | Returns Ex - 1 |
math.fabs() | Returns the absolute value of a number |
math.factorial() | Returns the factorial of a number |
math.floor() | Rounds a number down to the nearest integer |
math.fmod() | Returns the remainder of x/y |
math.frexp() | Returns the mantissa and the exponent, of a specified number |
math.fsum() | Returns the sum of all items in any iterable (tuples, arrays, lists, etc.) |
math.gamma() | Returns the gamma function at x |
math.gcd() | Returns the greatest common divisor of two integers |
math.hypot() | Returns the Euclidean norm |
math.isclose() | Checks whether two values are close to each other, or not |
math.isfinite() | Checks whether a number is finite or not |
math.isinf() | Checks whether a number is infinite or not |
math.isnan() | Checks whether a value is NaN (not a number) or not |
math.isqrt() | Rounds a square root number downwards to the nearest integer |
math.ldexp() | Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i |
math.lgamma() | Returns the log gamma value of x |
math.log() | Returns the natural logarithm of a number, or the logarithm of number to base |
math.log10() | Returns the base-10 logarithm of x |
math.log1p() | Returns the natural logarithm of 1+x |
math.log2() | Returns the base-2 logarithm of x |
math.perm() | Returns the number of ways to choose k items from n items with order and without repetition |
math.pow() | Returns the value of x to the power of y |
math.prod() | Returns the product of all the elements in an iterable |
math.radians() | Converts a degree value into radians |
math.remainder() | Returns the closest value that can make numerator completely divisible by the denominator |
math.sin() | Returns the sine of a number |
math.sinh() | Returns the hyperbolic sine of a number |
math.sqrt() | Returns the square root of a number |
math.tan() | Returns the tangent of a number |
math.tanh() | Returns the hyperbolic tangent of a number |
math.trunc() | Returns the truncated integer parts of a number |
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
Function | Description |
---|---|
findall | Returns a list containing all matches |
search | Returns a Match object if there is a match anywhere in the string |
split | Returns a list where the string has been split at each match |
sub | Replaces one or many matches with a string |
Character | Description | Example | |
---|---|---|---|
[] | A set of characters | "[a-m]" | |
\ | Signals a special sequence (can also be used to escape special characters) | "\d" | |
. | Any character (except newline character) | "he..o" | |
^ | Starts with | "^hello" | |
$ | Ends with | "planet$" | |
* | Zero or more occurrences | "he.*o" | |
+ | One or more occurrences | "he.+o" | |
? | Zero or one occurrences | "he.?o" | |
{} | Exactly the specified number of occurrences | "he.{2}o" | |
| | Either or | "falls|stays" | ]|
() | Capture and group |
Character | Description | Example |
---|---|---|
\A | Returns a match if the specified characters are at the beginning of the string | "\AThe" |
\b | Returns a match where the specified characters are at the beginning or at the end of a word (the "r" in the beginning is making sure that the string is being treated as a "raw string") |
r"\bain" r"ain\b" |
\B | Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word (the "r" in the beginning is making sure that the string is being treated as a "raw string") |
r"\Bain" r"ain\B" |
\d | Returns a match where the string contains digits (numbers from 0-9) | "\d" |
\D | Returns a match where the string DOES NOT contain digits | "\D" |
\s | Returns a match where the string contains a white space character | "\s" |
\S | Returns a match where the string DOES NOT contain a white space character | "\S" |
\w | Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) | "\w" |
\W | Returns a match where the string DOES NOT contain any word characters | "\W" |
\Z | Returns a match if the specified characters are at the end of the string | "Spain\Z" |
Set | Description |
---|---|
[arn] | Returns a match where one of the specified characters (a ,
r , or n ) is present
|
[a-n] | Returns a match for any lower case character, alphabetically between
a and n
|
[^arn] | Returns a match for any character EXCEPT a ,
r , and n
|
[0123] | Returns a match where any of the specified digits (0 ,
1 , 2 , or
3 ) are present
|
[0-9] | Returns a match for any digit between
0 and 9
|
[0-5][0-9] | Returns a match for any two-digit numbers from 00 and
59 |
[a-zA-Z] | Returns a match for any character alphabetically between
a and z , lower case OR upper case
|
[+] | In sets, + , * ,
. , | ,
() , $ ,{} has no special meaning, so [+] means: return a match for any
+ character in the string
|
import re
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
import re
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
try:
print(x)
except:
print("An exception occurred")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero"
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
f = open("demofile.txt", "r")
f = open("demofile.txt", "r")
print(f.read())
f = open("demofile.txt", "r")
print(f.readline())
f.close()
f.write("Woops! I have deleted the content!")
f = open("myfile.txt", "w")
import os
os.remove("demofile.txt")
import os
os.rmdir("myfolder")