代码清单2-1 索引操作示例
# Print out a date, given year, month, and day as numbers
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
# A list with one ending for each number from 1 to 31
endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
+ ['st', 'nd', 'rd'] + 7 * ['th'] \
+ ['st']
year = input('Year: ')
month = input('Month (1-12): ')
day = input('Day (1-31): ')
month_number = int(month)
day_number = int(day)
# Remember to subtract 1 from month and day to get a correct index
month_name = months[month_number-1]
ordinal = day + endings[day_number-1]
print(month_name + ' ' + ordinal + ', ' + year)
运行结果如下:
Year: 2022
Month (1-12): 10
Day (1-31): 21
October 21st, 2022
代码清单2-2 切片操作示例
# Split up a URL of the form http://www.something.com
url = input('Please enter the URL:')
domain = url[11:-4]
print("Domain name: " + domain)
运行结果如下:
Please enter the URL:http://www.python.org
Domain name: python
代码清单2-3 序列(字符串)乘法运算示例
# Prints a sentence in a centered "box" of correct width
sentence = input("Sentence: ")
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2
print()
print(' ' * left_margin + '+' + '-' * (box_width-2) + '+')
print(' ' * left_margin + '| ' + ' ' * text_width + ' |')
print(' ' * left_margin + '| ' + sentence + ' |')
print(' ' * left_margin + '| ' + ' ' * text_width + ' |')
print(' ' * left_margin + '+' + '-' * (box_width-2) + '+')
print()
运行结果如下:
Sentence: He's a very naughty boy!
+----------------------------+
| |
| He's a very naughty boy! |
| |
+----------------------------+
代码清单2-4 序列成员资格示例
# Check a user name and PIN code
database = [
['albert', '1234'],
['dilbert', '4242'],
['smith', '7524'],
['jones', '9843']
]
username = input('User name: ')
pin = input('PIN code: ')
if [username, pin] in database: print('Access granted')
运行结果如下:
User name: smith
PIN code: 7524
Access granted