Python编程快速上手 往让繁琐工作自动化-6.6 习题

Python编程快速上手 往让繁琐工作自动化-6.6 习题

1、什么是转义字符?

答:转义字符表示字符串中的一些字符,这些字符用别的方式很难在代码中打印出来。

2、转义字符\n和\t代表什么?

答:\n是换行符,\t是制表符。

3、如何在字符串中放入一个斜杠字符\?

答:\\转移字符表示一个反斜杠。

4、字符串"Howl's Moving Castle"是有效字符串。为什么单词中的单引号没有转义,却没有问题?

答:Howl's的单引号没有问题,因为你用了双引号看来标识字符串的开始和结束。

5、如果你不希望在字符串中加入\n,怎样写一个带有换行的字符串?

答:多行字符串让你在字符串中使用换行符,而不必用\n转义字符。

6、下面的表达式求值是什么?


'Hello world!'[1]
'Hello world!'[0:5]
'Hello world!'[:5]
'Hello world!'[3:]

答:
'Hello world!'[1] = e   
'Hello world!'[0:5] = Hello
'Hello world!'[:5] = Hello
'Hello world!'[3:] = lo world!

7、下面的表达式求值是什么?

'Hello'.upper()
'Hello'.upper().isupper()
'Hello'.upper().lower()
答:

'Hello'.upper() = HELLO
'Hello'.upper().isupper() = True
'Hello'.upper().lower() = hello

8、下面的表达式求值是什么?

'Remember, remember, the fifth of Novermber'.split()
'_'.join('There can be only one.').split()

答:
'Remember, remember, the fifth of Novermber'.split() = ['Remember,', 'remember,', 'the', 'fifth', 'of', 'Novermber']
'_'.join('There can be only one.').split()
'_'.join('There can be only one.').split() = ['T_h_e_r_e_', '_c_a_n_', '_b_e_', '_o_n_l_y_', '_o_n_e_.']

9、什么字符串方法能用于字符串右对齐、左对齐和居中?

答:
rjust()是右对齐
ljust()是左对齐
center()是居中


10、如何去掉字符串开始或末尾的空白字符?

答:
strip()是去掉两端的空白字符


6.7、实践项目-表格打印

    编写一个名为printTable()的函数,它接受字符串的列表的列表,将它显示在组织良好的表格中,每列
右对齐。假定所有内层列表都包含同样数目的字符串。例如,该值可能看起来像这样:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
            ['Alice', 'Bob', 'Carol', 'David'],
            ['dogs', 'cats', 'moose', 'goose']]

你的printTable()函数将打印出:
  apples   Alice  dogs
 oranges     Bob  cats
cherries   Carol moose
  banana   David goose

思路:用colWidths作为列表保存给定列表中最长字符串的宽度,找到colWidths列表中的最大值,
     再传递给rjust()字符串方法。

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: davie
"""
6.7、实践项目-表格打印
    编写一个名为printTable()的函数,它接受字符串的列表的列表,将它显示在组织良好的表格中,每列
右对齐。假定所有内层列表都包含同样数目的字符串。例如,该值可能看起来像这样:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
            ['Alice', 'Bob', 'Carol', 'David'],
            ['dogs', 'cats', 'moose', 'goose']]

你的printTable()函数将打印出:
  apples   Alice  dogs
 oranges     Bob  cats
cherries   Carol moose
  banana   David goose

"""
tableData = [['apples', 'oranges', 'cherries', 'banana'],
            ['Alice', 'Bob', 'Carol', 'David'],
            ['dogs', 'cats', 'moose', 'goose']]
def printTable(tabledata):
        len_list = [0,0,0]
        for index, item in enumerate(tableData):
                for str in item:
                        if len(str) > len_list[index]:
                                len_list[index] = len(str)
        #print(len_list)

        for seq in range(len(tableData)):
                print(tableData[0][seq].rjust(len_list[0]),
                      tableData[1][seq].rjust(len_list[1]),
                      tableData[2][seq].rjust(len_list[2])
                      )
printTable(tableData)

猜你喜欢

转载自www.cnblogs.com/bjx2020/p/9034700.html