python练习题

Django

第一题


s = "Alex SB 哈哈
x:1
y:2
z:3

自行车"

1. 如何取到["Alex SB 哈哈 x:1 y:2 z:3", "自行车"]?

ret = s.split('

')
print(ret)

2. 如何在上面结果基础上拿到["Alex", "SB", "哈哈"]?

ret = s.strip().split('
')
res = ret[0]  # Alex SB 哈哈
print(res.split(' '))  # ['Alex', 'SB', '哈哈']

3. 如何在上面结果基础上拿到"SB"?

print(res.split(' ')[1])

第二题


有一个列表,他的内部是一些元组,元组的第一个元素是姓名,第二个元素是爱好, 现在我给你一个姓名,如"Egon",如果有这个姓名,就打印出他的爱好,没有就打印查无此人

list1 = [
    ("Alex", "烫头"),
    ("Egon", "街舞"),
    ("Yuan", "喝茶"),
    ("Ya", "睡觉"),
]
name = input('请输入姓名 ').strip().title()
for i in list1:
    if i[0] == name:
        print("%(name)s's hobby is %(hobby)s" %({'name':name, 'hobby':i[1]}))
        break
else:
    print('查无此人')

第三题


我有一个HTML文件"login.html"

1. 我如何读取它的内容保存到变量html_s?

f = open('login.html', mode='r', encoding='utf-8')
html_s = f.read()
print(html_s)
f.close()

2. 我如何读取它的二进制内容保存到变量html_b?

f = open('login.html', mode='rb')
html_s = f.read()
print(html_s)
f.close()

3. 如何把s2转变成"Alex 花了一百万买了辆电动车,真SB。"

s2 = "Alex 花了一百万买了辆电动车,真@@xx@@。"
ret = s2.replace('@@xx@@', 'SB')
print(ret)

模块

第一题

1234能组成多少个不重复不相同的三位数?

from itertools import permutations

ret = permutations('1234', 3)
print(list(ret))

第二题

便利循环list1, list2

list1 = [11, 22, 33]
list2 = ['aa', 'bb', 'cc']
from itertools import chain

list1 = [11, 22, 33]
list2 = ['aa', 'bb', 'cc']

for i in chain(list1, list2):
    print(i)
原文地址:https://www.cnblogs.com/cjwnb/p/11715587.html