Python
Using python to interact with OS
Virtual Environment
$ pip install virtualenv
$ python3 -m venv env
$ source env/bin/activate
(env) $ deactivate
Division (/
) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the //
operator; to calculate the remainder you can use %
:
In interactive mode, the last printed expression is assigned to the variable _
. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations,
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
strings, which can be expressed in several ways. They can be enclosed in single quotes ('...'
) or double quotes ("..."
) with the same result 2. \
can be used to escape quotes
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated
concatenate variables or a variable and a literal, use +
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:>>>
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
Regular Expression
the regular expression test
will match the string test
exactly. (You can enable a case-insensitive mode that would let this RE match Test
or TEST
as well; more about this later.)
Hereβs a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO.
. ^ $ * + ? { } [ ] \ | ( )
A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For example,
^a...s$
The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and ending with s.
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
Last updated
Was this helpful?