实验2 字符串和列表

发布时间 2023-03-22 21:13:43作者: 刘权兴

实验任务1

task1.py

实验源码:

 

x = 'nba FIFA'
print(x.upper())
print(x.lower())
print(x.swapcase())
print()

x = 'abc'
print(x.center(10,'*'))
print (x.ljust(10,'*'))
print(x.rjust(10,'*'))
print()

x = '123'
print(x.zfill(10))
x = 123
print(str(x).zfill(10))
print()

x = 'phone_number'
print(x.isidentifier())
x = '222test'
print(x.isidentifier())
print()

x = ''
print(x.isspace())
x = '\n'
print(x.isspace())
print()

x = 'python is fun'
table = x.maketrans('thon','1234')
print(x.translate(table))

实验结果:

实验任务2

task2.py

实验源码:

x = [5, 11, 9, 7, 42]
print('整数输出1: ', end = '')
i = 0
while i < len(x):
    print(x[i], end = ' ')
    i += 1

print('\n整数输出2: ', end = '')
i = 0
while i < len(x):
    print(f'{x[i]:02d}', end = '-')
    i += 1

print('\n整数输出3: ', end = '')
i = 0
while i < len(x) - 1:
    print(f'{x[i]:02d}', end = '-')
    i += 1
print(f'{x[-1]:02d}')

print('\n字符输出1: ', end = '')
y1 = []
i = 0
while i < len(x):
    y1.append(str(x[i]))
    i += 1
print('-'.join(y1))

print('字符输出2: ', end = '')
y2 = []
i = 0
while i < len(x):
    y2.append( str(x[i]).zfill(2) )
    i += 1
print('-'.join(y2))

实验结果:

 

实验任务3

task3.py

实验源码:

name_list = ['david bowie', 'louis armstrong', 'leonard cohen', 'bob dylan', 'cocteau twins']
i = 0
while i < len(name_list):
    print(name_list[i].title())
    i += 1

print()

t = []
i = 0
while i < len(name_list):
    t.append(name_list[i].title())
    i += 1

print('\n'.join(t))

实验结果;

实验任务4

task4.py

实验源码: