CSC111 Exercises on Strings and Lists Indexes
--D. Thiebaut 09:24, 13 October 2011 (EDT)
The best reference: docs.python.org
Exercise 1
names = [ "Alice", "FRANK", "Lou", "maria", "JoSH" ]
- Print the names above in lowercase, with the first letter uppercase
- Center the names, one above the other, in a box of 40 characters
Exercise 2
- Given the following declaration
text = """A Tale of Two Cities | Charles Dickens | Historical fiction | English | 1859 | 200 million[1] The Lord of the Rings | J. R. R. Tolkien |High fantasy | English |1954–1955 |150 million[2] The Hobbit | J. R. R. Tolkien | Juvenile fantasy | English | 1937 | 100 million[3] Dream of the Red Chamber | Cao Xueqin | Historical fiction | Chinese | 1759-1791 | 100 million [4] And Then There Were None | Agatha Christie | Mystery | English | 1939 | 100 million[5]"""
- Write some code that will print out only the titles of the book, one above the other
- Write some more code that will print out the author followed by a colon, followed by the title
- Still some more code to display the title of the book and the number of books sold (last field on each line). See if you can print the number sold without the reference number in brackets.
Solutions
from graphics import *
def main():
#String exercises
names = [ "Alice", "FRANK", "Lou", "maria", "JoSH" ]
for name in names:
print( name.capitalize() )
width = 40
print( "+", "-" * (width-2), "+", sep='' )
for name in names:
print( "|", name.capitalize().center( width-2 ), "|", sep='' )
print( "+", "-" * (width-2), "+", sep='' )
# splitting text
text = """A Tale of Two Cities | Charles Dickens | Historical fiction | English | 1859 | 200 million[1]
The Lord of the Rings | J. R. R. Tolkien |High fantasy | English |1954–1955 |150 million[2]
The Hobbit | J. R. R. Tolkien | Juvenile fantasy | English | 1937 | 100 million[3]
Dream of the Red Chamber | Cao Xueqin | Historical fiction | Chinese | 1759-1791 | 100 million [4]
And Then There Were None | Agatha Christie | Mystery | English | 1939 | 100 million[5]"""
lines = text.split( "\n" )
for line in lines:
fields = line.split( '|' )
title = fields[ 0 ]
print( title.strip() )
for line in lines:
title, author, Type, language, year, sold = line.split( '|' )
print( author.strip(), ': ', title.strip(), sep='' )
for line in lines:
title, author, Type, language, year, sold = line.split( '|' )
sold = sold.split( '[' )[0]
print( title.strip(), ' has sold ', sold.strip(), ' volumes', sep='' )
main()