Python exam help: Difference between revisions
From ICO wiki
Jump to navigationJump to search
Line 248: | Line 248: | ||
==Exam answer== | ==Exam answer== | ||
import shutil, sys, magic, os | import shutil, sys, magic, os | ||
from mutagen.easyid3 import EasyID3 | from mutagen.easyid3 import EasyID3 | ||
Line 288: | Line 288: | ||
shutil.copy(path, os.path.join(output_directory, directory_name, target_name)) | shutil.copy(path, os.path.join(output_directory, directory_name, target_name)) | ||
print "Move from:", filename, "to:", os.path.join(directory_name, target_name) | print "Move from:", filename, "to:", os.path.join(directory_name, target_name) | ||
</source> | |||
==EXAMPLE== | |||
<source lang="python"> | |||
SLICING | |||
#Slice syntax forms: | |||
Get elements from... | |||
values[1:3] Index 1 through index 3. | |||
values[2:-1] Index 2 through index one from last. | |||
values[:2] Start through index 2. | |||
values[2:] Index 2 through end. | |||
values[::2] Start through end, skipping ahead 2 places each time. | |||
............................................................... | |||
#Python program that slices list | |||
values = [100, 200, 300, 400, 500] | |||
# Get elements from second index to third index. | |||
slice = values[1:3] | |||
print(slice) | |||
Output | |||
[200, 300] | |||
.................................... | |||
#Python that creates slice object | |||
# Create a slice object. | |||
example = slice(1, 10, 0) | |||
print(example.start, example.stop, example.step) | |||
Output | |||
1 10 0 | |||
....................................................... | |||
#Python program that resizes list | |||
letters = ["x", "y", "z", "a", "b"] | |||
print(letters) | |||
# Resize list to two elements at the start. | |||
letters = letters[:2] | |||
print(letters) | |||
Output | |||
['x', 'y', 'z', 'a', 'b'] | |||
['x', 'y'] | |||
........................................ | |||
#Python program that reduces size | |||
values = [10, 20, 30, 40, 50] | |||
print(values) | |||
# Reduce size of list by 2 elements. | |||
values = values[:-2] | |||
print(values) | |||
Output | |||
[10, 20, 30, 40, 50] | |||
[10, 20, 30] | |||
............................................ | |||
#Python program that slices, starts and ends | |||
values = [100, 200, 300, 400, 500] | |||
# Slice from start to second index. | |||
slice = values[:2] | |||
print(slice) | |||
# Slice from second index to end. | |||
slice = values[2:] | |||
print(slice) | |||
Output | |||
[100, 200] | |||
[300, 400, 500] | |||
......................................... | |||
#Python program that slices string | |||
word = "something" | |||
# Get first four characters. | |||
part = word[:4] | |||
print(part) | |||
Output | |||
some | |||
............................................... | |||
#Python program that locates relative slices | |||
def between(value, a, b): | |||
# Find and validate before-part. | |||
pos_a = value.find(a) | |||
if pos_a == -1: return "" | |||
# Find and validate after part. | |||
pos_b = value.rfind(b) | |||
if pos_b == -1: return "" | |||
# Return middle part. | |||
adjusted_pos_a = pos_a + len(a) | |||
if adjusted_pos_a >= pos_b: return "" | |||
return value[adjusted_pos_a:pos_b] | |||
def before(value, a): | |||
# Find first part and return slice before it. | |||
pos_a = value.find(a) | |||
if pos_a == -1: return "" | |||
return value[0:pos_a] | |||
def after(value, a): | |||
# Find and validate first part. | |||
pos_a = value.rfind(a) | |||
if pos_a == -1: return "" | |||
# Returns chars after the found string. | |||
adjusted_pos_a = pos_a + len(a) | |||
if adjusted_pos_a >= len(value): return "" | |||
return value[adjusted_pos_a:] | |||
# Test the methods with this literal. | |||
test = "DEFINE:A=TWO" | |||
print(between(test, "DEFINE:", "=")) | |||
print(between(test, ":", "=")) | |||
print(before(test, ":")) | |||
print(before(test, "=")) | |||
print(after(test, ":")) | |||
print(after(test, "DEFINE:")) | |||
print(after(test, "=")) | |||
Output | |||
A | |||
A | |||
DEFINE | |||
DEFINE:A | |||
A=TWO | |||
A=TWO | |||
TWO | |||
............................ | |||
#copy list | |||
ython program that copies list | |||
# A list: | |||
list1 = [10, 20, 30] | |||
# Copy list1 with slice syntax. | |||
list2 = list1[:] | |||
# Modify list2. | |||
list2[0] = 0 | |||
print(list1) | |||
print(list2) | |||
Output | |||
[10, 20, 30] | |||
[0, 20, 30] | |||
.......................... | |||
#Extend | |||
Python program that uses extend, copies list | |||
list1 = [10, 20, 30] | |||
# Create empty list, then extend it. | |||
list2 = [] | |||
list2.extend(list1) | |||
# The lists are separate. | |||
list2[0] = 0 | |||
print(list1) | |||
print(list2) | |||
Output | |||
[10, 20, 30] | |||
[0, 20, 30] | |||
.................... | |||
#slicing | |||
ex:1 | |||
s = "abcdefghijklmnopqrs" | |||
# Loop over some indexes. | |||
for n in range(2, 4): | |||
#Print slices. | |||
print(n, s[n]) #(2, 'c') (3, 'd') | |||
print(n, s[n:n + 2]) #(2, 'cd')(3, 'de') | |||
print(n, s[n:n + 3]) #(2, 'cde')(3, 'def') | |||
print(n, s[n:n + 4:2]) #(2, 'ce')(3, 'df') | |||
print(n, s[n:n + 6:2]) #(2, 'ceg')(3, 'dfh') | |||
............. | |||
#Normally, you would just do: | |||
s = s[:-3] + s[-2:] | |||
The s[:-3] gives you a string up to, but not including, the comma you want removed ("this is a string") and the s[-2:] gives you another string starting one character beyond that comma (" a"). | |||
Then, joining the two strings together gives you what you were after ("this is a string a"). | |||
..................... | |||
#ANother example. | |||
>>> t = (2, 5, 7, 9, 10, 11, 12) | |||
>>> t[2:4] | |||
(7, 9) | |||
................. | |||
#splitting string | |||
ex:1 | |||
x = 'blue,red,green' | |||
x.split(",") | |||
['blue', 'red', 'green'] | |||
>>> | |||
>>> a,b,c = x.split(",") | |||
>>> a | |||
'blue' | |||
>>> b | |||
'red' | |||
>>> c | |||
'green' | |||
ex:2 | |||
>>> word = "This is some random text" | |||
>>> words2 = word.split(" ") | |||
>>> words | |||
['This', 'is', 'some', 'random', 'text'] | |||
................ | |||
#SPILITTING ANOTHER METHOD | |||
Following is the syntax for split() method − | |||
str.split(str="", num=string.count(str)). | |||
Ex:1 | |||
#!/usr/bin/python | |||
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"; | |||
print str.split( ) | |||
print str.split(' ', 1 ) | |||
output: | |||
'Line1-abcdef', 'Line2-abc', 'Line4-abcd'] | |||
['Line1-abcdef', '\nLine2-abc \nLine4-abcd'] | |||
................................................... | |||
#JOINING STRING | |||
Following is the syntax for join() method: | |||
str.join(sequence) | |||
Example1: | |||
he following example shows the usage of join() method. | |||
#!/usr/bin/python | |||
s = "-"; | |||
seq = ("a", "b", "c"); # This is sequence of strings. | |||
print s.join( seq ) | |||
When we run above program, it produces following result − | |||
a-b-c | |||
............................. | |||
#String Formatting | |||
String formatting with % | |||
ex:1 | |||
x = 'apple' | |||
y = 'lemon' | |||
z = "The items in the basket are %s and %s" % (x,y) | |||
................................ | |||
#String formatting using { } | |||
ex:1 | |||
fname = "Joe" | |||
lname = "Who" | |||
age = "24" | |||
#Example of how to use the format() method: | |||
print "{} {} is {} years ".format(fname, lname, age) | |||
Another really cool thing is that we don't have to provide the inputs in the same order, if we number the place-holders. | |||
print "{0} {1} is {2} years".format(fname, lname, age) | |||
............................... | |||
#Python program that gets one-character substring | |||
value = "web" | |||
# Loop over every index in string. | |||
for index in range(0, len(value)): | |||
# Get one-character substring. | |||
char = value[index] | |||
# Display substring. | |||
print(char) | |||
# Test substring. | |||
if char == "w": | |||
print(True) | |||
Output: | |||
w | |||
True | |||
e | |||
b | |||
................... | |||
#Python program that takes substrings | |||
string = "abcdefgh" | |||
# Two-character substring. | |||
two = string[0:2] | |||
# Three-character substring. | |||
three = string[0:3] | |||
# Four-character substring. | |||
four = string[0:4] | |||
# Five-character substring. | |||
five = string[0:5] | |||
print(two) | |||
print(three) | |||
print(four) | |||
print(five) | |||
Output: | |||
ab | |||
abc | |||
abcd | |||
abcde | |||
...................................................... | |||
#Python program that uses offset | |||
string = "abcdefgh" | |||
# Three characters starting at index 2. | |||
offset = 2 | |||
length = 3 | |||
sliced = string[offset:offset+length] | |||
print(sliced) | |||
Output | |||
cde | |||
........................ | |||
#Python program that omits start index | |||
value = "google" | |||
# Omitting the start means start at 0. | |||
test1 = value[:2] | |||
test2 = value[0:2] | |||
print(test1) | |||
print(test2) | |||
Output | |||
go | |||
go | |||
.............................. | |||
#Python program that gets last two characters | |||
value = "apple" | |||
# Get last two characters. | |||
end = value[-2:] | |||
print(end) | |||
Output | |||
le | |||
........................... | |||
#Python that causes error | |||
value = "dotperls" | |||
value[3] = " net " # Does not work. | |||
print(value) | |||
Output | |||
Traceback (most recent call last): | |||
File "...\file.py", line 6, in <module> | |||
value[3:] = " net " | |||
TypeError: 'str' object does not support item assignment | |||
...................................................... | |||
#Python that uses slice, gets first words | |||
def first_words(input, words): | |||
for i in range(0, len(input)): | |||
# Count spaces in the string. | |||
if input[i] == ' ': | |||
words -= 1 | |||
if words == 0: | |||
# Return the slice up to this point. | |||
return input[0:i] | |||
return "" | |||
# Test our method. | |||
test = "Stately, plump Buck Mulligan came from the stairhead." | |||
result = first_words(test, 4) | |||
print(result) | |||
Output | |||
Stately, plump Buck Mulligan | |||
.......................................................... | |||
#Python program that truncates string | |||
value = "one two three" | |||
# Truncate the string to 3 characters. | |||
first = value[0:3] | |||
print(first + ".") | |||
# Truncate the string to 7 characters. | |||
second = value[0:7] | |||
print(second + ".") | |||
Output | |||
one. | |||
one two. | |||
.......................................... | |||
#Python program that uses short truncation syntax | |||
letters = "abcdef" | |||
# Omit the first 0 in the slice syntax. | |||
# ... This truncates the string. | |||
first_part = letters[:3] | |||
print(first_part) | |||
Output | |||
abc | |||
............................... | |||
#LIST MANIPULATING | |||
first we need an example list: | |||
x = [1,6,3,2,6,1,2,6,7] | |||
# lets add something. | |||
# we can do .append, which will add something to the end of the list, like: | |||
x.append(55) | |||
print(x) | |||
Above, we took a list, and added to the end of the list with .append. Remember append with files? Same thing, .append() will add to the end of a list. | |||
....... | |||
x.insert(2,33) | |||
print(x) | |||
Here we say that we want to insert, at the index of 2, the number 33. The reason that went in the 3rd place, again, is because we start at the zero element, then go 1, 2...etc with lists. | |||
......... | |||
x.remove(6) | |||
print(x) | |||
Now we can remove things. .remove() will remove the first instance of the value in the list. If it doesn't exist, there will be an error: | |||
........... | |||
Next, remember how we can reference an item by index in a list? like: | |||
print(x[5]) | |||
................ | |||
Well, we can also search for this index, like so: | |||
print(x.index(1)) | |||
............. | |||
Now here, we can see that it actually returned a 0, meaning the first element was a 1... when we knew there was another with an index of 5. So, instead we might want to know before-hand how many examples there are. | |||
print(x.count(1)) | |||
We see there are actually 2 of them | |||
We can also sort the list: | |||
x.sort() | |||
print(x) | |||
What if these were strings? like: | |||
y = ['Jan','Dan','Bob','Alice','Jon','Jack'] | |||
y.sort() | |||
print(y) | |||
y.reverse() | |||
print(y) | |||
....................................... | |||
#DICT | |||
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example − | |||
#!/usr/bin/python | |||
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} | |||
print "dict['Name']: ", dict['Name'] | |||
print "dict['Age']: ", dict['Age'] | |||
When the above code is executed, it produces the following result − | |||
dict['Name']: Zara | |||
dict['Age']: 7 | |||
............................... | |||
#Updating Dictionary | |||
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example − | |||
#!/usr/bin/python | |||
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} | |||
dict['Age'] = 8; # update existing entry | |||
dict['School'] = "DPS School"; # Add new entry | |||
print "dict['Age']: ", dict['Age'] | |||
print "dict['School']: ", dict['School'] | |||
When the above code is executed, it produces the following result − | |||
dict['Age']: 8 | |||
dict['School']: DPS School | |||
..................................... | |||
#Example Dict value | |||
The following example shows the usage of values() method. | |||
#!/usr/bin/python | |||
dict = {'Name': 'Zara', 'Age': 7} | |||
print "Value : %s" % dict.values() | |||
When we run above program, it produces following result − | |||
Value : [7, 'Zara'] | |||
.......................... | |||
#Dict default key | |||
dict.setdefault(key, default=None) | |||
he following example shows the usage of setdefault() method. | |||
#!/usr/bin/python | |||
dict = {'Name': 'Zara', 'Age': 7} | |||
print "Value : %s" % dict.setdefault('Age', None) | |||
print "Value : %s" % dict.setdefault('Sex', None) | |||
When we run above program, it produces following result − | |||
Value : 7 | |||
Value : None | |||
Dict items | |||
The following example shows the usage of items() method. | |||
#!/usr/bin/python | |||
dict = {'Name': 'Zara', 'Age': 7} | |||
print "Value : %s" % dict.items() | |||
When we run above program, it produces following result − | |||
Value : [('Age', 7), ('Name', 'Zara')] | |||
</source> | </source> |
Latest revision as of 12:50, 7 June 2016
To get GPS coordinates and image orientation:
from exifread import process_file
def degrees(j):
return j.values[0].num + (j.values[1].num + j.values[2].den * 1.0 / j.values[2].num) / 60.0
tags = process_file(open("/home/sheela/Documents/Python/pics/IMG_20131019_201706.jpg"))
print tags
lat, lng = tags.get("GPS GPSLatitude"), tags.get("GPS GPSLongitude")
if lat and lng:
print "%.4f,%.4f" % (degrees(lat), degrees(lng)),
# Parse datetime of the photo
timestamp = tags.get("EXIF DateTimeOriginal")
if timestamp:
print timestamp.values,
# Parse image orientation
orientation = tags.get("Image Orientation")
if orientation:
j, = orientation.values
if j == 6:
print "rotated 270 degrees",
elif j == 8:
print "rotated 90 degrees",
elif j == 3:
print "rotated 180 degrees",
print
This code is to remove the exif data - metadata
import Image
from exifread import process_file
image_file = open('/home/sheela/Documents/Python/pics/IMG_20150619_120040.jpg')
image = Image.open(image_file)
# next 3 lines strip exif
data = list(image.getdata())
image_without_exif = Image.new(image.mode, image.size)
image_without_exif.putdata(data)
image_without_exif.save('without_exif_data.jpeg')
This code is to rotate the picture (which do not have metadata) to original view
import Image
orig = Image.open("original.jpg")
rotated = orig.transpose(Image.ROTATE_90) # This happens only in the RAM!
rotated.save("rotated.jpg")
import Image
from exifread import process_file
#input_path, output_path = sys.argv[1:]
image_file = open('/home/sheela/Documents/Python/pics/IMG_20131019_201706.jpg')
image = Image.open(image_file)
# next 3 lines strip exif
data = list(image.getdata())
image_without_exif = Image.new(image.mode, image.size)
image_without_exif.putdata(data)
image_without_exif.save('without_exif_data.jpeg')
im = Image.open("/home/sheela/Documents/Python/pics/IMG_20131019_201706.jpg")
rotated = im.transpose(Image.ROTATE_90)
im.save("rotated.jpg")
#orig = Image.open(output_path)
#rotated = orig.transpose(Image.ROTATE_90) # This happens only in the RAM!
#rotated.save(output_path)
dexif.py Lauri's code
import codecs, os, sys
from exifread import process_file
from PIL import Image
from jinja2 import Template
input_path, output_path = sys.argv[1:]
if not os.path.exists(output_path):
os.makedirs(os.path.join(output_path, "thumbnails"))
template = Template(codecs.open("gallery.html", "r", encoding="utf-8").read())
with codecs.open("/tmp/bulid/index.html", "w", encoding="utf-8") as fh:
fh.write(template.render(files = os.listdir(input_path)))
for filename in os.listdir(input_path):
if not filename.endswith(".jpg"): continue
print filename
tags = EXIF.process_file(open(os.path.join(input_path, filename)))
im = Image.open(os.path.join(input_path, filname))
rotated = im # Not roated at all
orientation = tags.get("Image orientation") # paese image orientation
if orientation:
j, = orientation.values
if j == 6:
rotated = im.transpose(Image.ROTATE_270)
elif j == 8:
rotated = im.transpose(Image.ROTATE_90)
elif j == 3:
rotated = im.transpose(Image.ROTATE_180)
rotated.save(os.path.join(output_path, filename))
rotated.thumbnail((192,192), Image.ANTIALIAS)
rotated.save(os.path.join(output_path, "thumbnails", filename))
Artur code A.py
import Image
import sys
from exifread import process_file
input_path, output_path = sys.argv[1:]
image_file = open(input_path)
image = Image.open(image_file)
data = list(image.getdata())
no_exif = Image.new(image.mode, image.size)
no_exif.putdata(data)
no_exif.save(output_path)
orig = Image.open(output_path)
rotated = orig.transpose(Image.ROTATE_90) # This happens only in the RAM!
rotated.save(output_path)
To get image thumbnail
<<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Images</title>
<style>
body {
background-color: #444;
}
.thumbnail {
position: relative;
display: inline;
margin: 1em;
padding: 0;
width: 192;
height: 192;
box-shadow: 0px 0px 10px rgba(0,0,0,1);
}
</style>
</head>
<body>
{% for filename in files %
<a href= "{{filename}}">
<img class="thumbnail" src="thumbnails/{{filename}}"/>
</a>
{% endfor %}
</body>
</html>
Final result all in one file
# I need to mention my path like this - python dexif2.py /home/sheela/Documents/Python/pics /home/sheela/Documents/Python
import codecs, os,sys
from exifread import process_file
from PIL import Image
from jinja2 import Template
# Grab arguments specified on the command line after: python paranoia.py <input_dir> <output_dir>
input_directory, output_directory = sys.argv[1:]
# Create output directories if necessary
if not os.path.exists(output_directory):
os.makedirs(os.path.join(output_directory, "thumbnails"))
HEADER = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
body { background-color: #444; }
img.thumb { position: relative; display: inline; margin: 1em;
padding: 0; width: 192; height: 192;
box-shadow: 0px 0px 10px rgba(0,0,0,1); }
</style>
</head>
<body>
"""
# Open index.html in output diretory and write it line by line
with open(os.path.join(output_directory, "index.html"), "w") as fh:
fh.write(HEADER)
for filename in os.listdir(input_directory):
# Read EXIF tags
tags = process_file(open(os.path.join(input_directory, filename)))
# Read image data
original = Image.open(os.path.join(input_directory, filename))
# Rotate as necessary
rotated = original # Not rotated at all
orientation = tags.get("Image Orientation") # Parse image orientation
if orientation:
j, = orientation.values
if j == 6:
rotated = original.transpose(Image.ROTATE_270)
elif j == 8:
rotated = original.transpose(Image.ROTATE_90)
elif j == 3:
rotated = original.transpose(Image.ROTATE_180)
rotated.save(os.path.join(output_directory, filename))
# Save thumbnail
rotated.thumbnail((192,192), Image.ANTIALIAS)
rotated.save(os.path.join(output_directory, "thumbnails", filename))
fh.write(""" <a href="%s">""" % filename)
fh.write("""<img class="thumb" src="thumbnails/%s"/>""" % filename)
fh.write("""</a>\n""")
fh.write(" </body>\n")
fh.write("</html>\n")
Exam answer
import shutil, sys, magic, os from mutagen.easyid3 import EasyID3 from mutagen.id3 import ID3NoHeaderError
db = magic.open(magic.MAGIC_MIME_TYPE) db.load()
try:
input_directory, output_directory = sys.argv[1:3]
except ValueError:
print "Not enough arguments!" sys.exit(255)
for filename in os.listdir(input_directory):
path = os.path.join(input_directory, filename) if db.file(path) not in ("application/octet-stream", "audio/mpeg"): continue try: tags = EasyID3(path) except ID3NoHeaderError: continue artist, = tags.get("artist") # artist = tags.get("artist")[0] album, = tags.get("album") title, = tags.get("title") year, = tags.get("date") tracknumber, = tags.get("tracknumber") if "/" in tracknumber: tracknumber, _ = tracknumber.split("/") directory_name = "%s - %s (%s)" % (artist, album, year) target_name = "%02d. %s - %s.mp3" % (int(tracknumber), artist, title) if not os.path.exists(os.path.join(output_directory, directory_name)): os.makedirs(os.path.join(output_directory, directory_name)) shutil.copy(path, os.path.join(output_directory, directory_name, target_name)) print "Move from:", filename, "to:", os.path.join(directory_name, target_name)
</source>
EXAMPLE
SLICING
#Slice syntax forms:
Get elements from...
values[1:3] Index 1 through index 3.
values[2:-1] Index 2 through index one from last.
values[:2] Start through index 2.
values[2:] Index 2 through end.
values[::2] Start through end, skipping ahead 2 places each time.
...............................................................
#Python program that slices list
values = [100, 200, 300, 400, 500]
# Get elements from second index to third index.
slice = values[1:3]
print(slice)
Output
[200, 300]
....................................
#Python that creates slice object
# Create a slice object.
example = slice(1, 10, 0)
print(example.start, example.stop, example.step)
Output
1 10 0
.......................................................
#Python program that resizes list
letters = ["x", "y", "z", "a", "b"]
print(letters)
# Resize list to two elements at the start.
letters = letters[:2]
print(letters)
Output
['x', 'y', 'z', 'a', 'b']
['x', 'y']
........................................
#Python program that reduces size
values = [10, 20, 30, 40, 50]
print(values)
# Reduce size of list by 2 elements.
values = values[:-2]
print(values)
Output
[10, 20, 30, 40, 50]
[10, 20, 30]
............................................
#Python program that slices, starts and ends
values = [100, 200, 300, 400, 500]
# Slice from start to second index.
slice = values[:2]
print(slice)
# Slice from second index to end.
slice = values[2:]
print(slice)
Output
[100, 200]
[300, 400, 500]
.........................................
#Python program that slices string
word = "something"
# Get first four characters.
part = word[:4]
print(part)
Output
some
...............................................
#Python program that locates relative slices
def between(value, a, b):
# Find and validate before-part.
pos_a = value.find(a)
if pos_a == -1: return ""
# Find and validate after part.
pos_b = value.rfind(b)
if pos_b == -1: return ""
# Return middle part.
adjusted_pos_a = pos_a + len(a)
if adjusted_pos_a >= pos_b: return ""
return value[adjusted_pos_a:pos_b]
def before(value, a):
# Find first part and return slice before it.
pos_a = value.find(a)
if pos_a == -1: return ""
return value[0:pos_a]
def after(value, a):
# Find and validate first part.
pos_a = value.rfind(a)
if pos_a == -1: return ""
# Returns chars after the found string.
adjusted_pos_a = pos_a + len(a)
if adjusted_pos_a >= len(value): return ""
return value[adjusted_pos_a:]
# Test the methods with this literal.
test = "DEFINE:A=TWO"
print(between(test, "DEFINE:", "="))
print(between(test, ":", "="))
print(before(test, ":"))
print(before(test, "="))
print(after(test, ":"))
print(after(test, "DEFINE:"))
print(after(test, "="))
Output
A
A
DEFINE
DEFINE:A
A=TWO
A=TWO
TWO
............................
#copy list
ython program that copies list
# A list:
list1 = [10, 20, 30]
# Copy list1 with slice syntax.
list2 = list1[:]
# Modify list2.
list2[0] = 0
print(list1)
print(list2)
Output
[10, 20, 30]
[0, 20, 30]
..........................
#Extend
Python program that uses extend, copies list
list1 = [10, 20, 30]
# Create empty list, then extend it.
list2 = []
list2.extend(list1)
# The lists are separate.
list2[0] = 0
print(list1)
print(list2)
Output
[10, 20, 30]
[0, 20, 30]
....................
#slicing
ex:1
s = "abcdefghijklmnopqrs"
# Loop over some indexes.
for n in range(2, 4):
#Print slices.
print(n, s[n]) #(2, 'c') (3, 'd')
print(n, s[n:n + 2]) #(2, 'cd')(3, 'de')
print(n, s[n:n + 3]) #(2, 'cde')(3, 'def')
print(n, s[n:n + 4:2]) #(2, 'ce')(3, 'df')
print(n, s[n:n + 6:2]) #(2, 'ceg')(3, 'dfh')
.............
#Normally, you would just do:
s = s[:-3] + s[-2:]
The s[:-3] gives you a string up to, but not including, the comma you want removed ("this is a string") and the s[-2:] gives you another string starting one character beyond that comma (" a").
Then, joining the two strings together gives you what you were after ("this is a string a").
.....................
#ANother example.
>>> t = (2, 5, 7, 9, 10, 11, 12)
>>> t[2:4]
(7, 9)
.................
#splitting string
ex:1
x = 'blue,red,green'
x.split(",")
['blue', 'red', 'green']
>>>
>>> a,b,c = x.split(",")
>>> a
'blue'
>>> b
'red'
>>> c
'green'
ex:2
>>> word = "This is some random text"
>>> words2 = word.split(" ")
>>> words
['This', 'is', 'some', 'random', 'text']
................
#SPILITTING ANOTHER METHOD
Following is the syntax for split() method −
str.split(str="", num=string.count(str)).
Ex:1
#!/usr/bin/python
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( )
print str.split(' ', 1 )
output:
'Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
...................................................
#JOINING STRING
Following is the syntax for join() method:
str.join(sequence)
Example1:
he following example shows the usage of join() method.
#!/usr/bin/python
s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )
When we run above program, it produces following result −
a-b-c
.............................
#String Formatting
String formatting with %
ex:1
x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s" % (x,y)
................................
#String formatting using { }
ex:1
fname = "Joe"
lname = "Who"
age = "24"
#Example of how to use the format() method:
print "{} {} is {} years ".format(fname, lname, age)
Another really cool thing is that we don't have to provide the inputs in the same order, if we number the place-holders.
print "{0} {1} is {2} years".format(fname, lname, age)
...............................
#Python program that gets one-character substring
value = "web"
# Loop over every index in string.
for index in range(0, len(value)):
# Get one-character substring.
char = value[index]
# Display substring.
print(char)
# Test substring.
if char == "w":
print(True)
Output:
w
True
e
b
...................
#Python program that takes substrings
string = "abcdefgh"
# Two-character substring.
two = string[0:2]
# Three-character substring.
three = string[0:3]
# Four-character substring.
four = string[0:4]
# Five-character substring.
five = string[0:5]
print(two)
print(three)
print(four)
print(five)
Output:
ab
abc
abcd
abcde
......................................................
#Python program that uses offset
string = "abcdefgh"
# Three characters starting at index 2.
offset = 2
length = 3
sliced = string[offset:offset+length]
print(sliced)
Output
cde
........................
#Python program that omits start index
value = "google"
# Omitting the start means start at 0.
test1 = value[:2]
test2 = value[0:2]
print(test1)
print(test2)
Output
go
go
..............................
#Python program that gets last two characters
value = "apple"
# Get last two characters.
end = value[-2:]
print(end)
Output
le
...........................
#Python that causes error
value = "dotperls"
value[3] = " net " # Does not work.
print(value)
Output
Traceback (most recent call last):
File "...\file.py", line 6, in <module>
value[3:] = " net "
TypeError: 'str' object does not support item assignment
......................................................
#Python that uses slice, gets first words
def first_words(input, words):
for i in range(0, len(input)):
# Count spaces in the string.
if input[i] == ' ':
words -= 1
if words == 0:
# Return the slice up to this point.
return input[0:i]
return ""
# Test our method.
test = "Stately, plump Buck Mulligan came from the stairhead."
result = first_words(test, 4)
print(result)
Output
Stately, plump Buck Mulligan
..........................................................
#Python program that truncates string
value = "one two three"
# Truncate the string to 3 characters.
first = value[0:3]
print(first + ".")
# Truncate the string to 7 characters.
second = value[0:7]
print(second + ".")
Output
one.
one two.
..........................................
#Python program that uses short truncation syntax
letters = "abcdef"
# Omit the first 0 in the slice syntax.
# ... This truncates the string.
first_part = letters[:3]
print(first_part)
Output
abc
...............................
#LIST MANIPULATING
first we need an example list:
x = [1,6,3,2,6,1,2,6,7]
# lets add something.
# we can do .append, which will add something to the end of the list, like:
x.append(55)
print(x)
Above, we took a list, and added to the end of the list with .append. Remember append with files? Same thing, .append() will add to the end of a list.
.......
x.insert(2,33)
print(x)
Here we say that we want to insert, at the index of 2, the number 33. The reason that went in the 3rd place, again, is because we start at the zero element, then go 1, 2...etc with lists.
.........
x.remove(6)
print(x)
Now we can remove things. .remove() will remove the first instance of the value in the list. If it doesn't exist, there will be an error:
...........
Next, remember how we can reference an item by index in a list? like:
print(x[5])
................
Well, we can also search for this index, like so:
print(x.index(1))
.............
Now here, we can see that it actually returned a 0, meaning the first element was a 1... when we knew there was another with an index of 5. So, instead we might want to know before-hand how many examples there are.
print(x.count(1))
We see there are actually 2 of them
We can also sort the list:
x.sort()
print(x)
What if these were strings? like:
y = ['Jan','Dan','Bob','Alice','Jon','Jack']
y.sort()
print(y)
y.reverse()
print(y)
.......................................
#DICT
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result −
dict['Name']: Zara
dict['Age']: 7
...............................
#Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result −
dict['Age']: 8
dict['School']: DPS School
.....................................
#Example Dict value
The following example shows the usage of values() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.values()
When we run above program, it produces following result −
Value : [7, 'Zara']
..........................
#Dict default key
dict.setdefault(key, default=None)
he following example shows the usage of setdefault() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.setdefault('Age', None)
print "Value : %s" % dict.setdefault('Sex', None)
When we run above program, it produces following result −
Value : 7
Value : None
Dict items
The following example shows the usage of items() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.items()
When we run above program, it produces following result −
Value : [('Age', 7), ('Name', 'Zara')]