文章目录

    • 适用专业
    • 实验目的
    • 实验内容
    • Code
    • 附加:字符串的ljust、rjust、center方法

适用专业

适用于所有专业

实验目的

  1. 熟练掌握内置函数open()的用法
  2. 熟练运用内置函数len()、max()、enumerate()。
  3. 熟练运用字符串的strip()、ljust()和其他方法。
  4. 熟练运用列表推导式。

实验内容

编写一个程序demo.py,要求运行该程序后,生成demo_.new.py文件,其中内容与demo.py一样,只是在每一行的后面加上行号。要求行号以#开始,并且所有行的#垂直对齐。

Code

#Python实验25
filename = 'demo.py'
with open(filename,'r') as fp:
    lines = fp.readline()
maxlength = len(max(lines,key = len))
lines = [lines.rstrip().ljust(maxlength) + '#' + str(index) + '\n'
         for index,line in enumerate(lines)]
with open(filename[:-3]+'_new.py','w') as fp:
    fp.writelines(lines)

附加:字符串的ljust、rjust、center方法

>>> a="Hello world"

>>> print a.rjust(20)

' Hello world'

>>> print a.ljust(20)

'Hello world '

>>> print a.center(20)

' Hello world '

>>> print a.rjust(20,'*')

'*********Hello world'

>>> print a.ljust(20,'*')

'Hello world*********'

>>> print a.center(20,'*')

'****Hello world*****'

本文地址:https://blog.csdn.net/Kinght_123/article/details/110423701