python学习笔记 第六章

来源:互联网 发布:淘宝全屏首页怎么上传 编辑:程序博客网 时间:2024/05/24 06:17
#转义字符与原始字符print("Hello there!\nHow are you?\nI\'m doing fine.")print('Say hi to Bob\'s mother.')print(r'Say hi to Bob\'s mother.')print()#用三重引号的多行字符串print('''Dear Alice,Eve's cat has been arrested for catnapping, cat burglary, and extortion.Sincerely,Bob''')

Hello there!
How are you?
I'm doing fine.
Say hi to Bob's mother.
Say hi to Bob\'s mother.


Dear Alice,


Eve's cat has been arrested for catnapping, cat burglary, and extortion.


Sincerely,


Bob


多行注释只能用于函数的一开始,在函数中间位置用会有问题

"""This is a test Python program.Written by Al Sweigart al@inventwithpython.comThis program was designed for Python 3, not Python 2."""def spam():    """This is a multiline comment to help    explain what the spam() function does."""    print('Hello!')

isX 字符串方法:

#isalpha()返回 True 如果字符串只包含字母, 并且非空;print("hello only alpha:"+str('hello'.isalpha()))print("hello321 only alpha:"+str('hello321'.isalpha()))#isalnum()返回 True,如果字符串只包含字母和数字,并且非空;print(str("321l123 is number or alpha:"+str("321l123".isalnum())))#isdecimal()返回 True,如果字符串只包含数字字符,并且非空;print(str("321123 only number:"+str("321123".isdecimal())))#isspace()返回 True,如果字符串只包含空格、制表符和换行,并且非空;print(str("321123 is number:"+str("321123".isspace())))#istitle()返回 True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词print('This Is NOT Title Case Either'.istitle())print('This Is Title Case 123'.istitle())print('This Is Not Title Case Either'.istitle())
hello only alpha:True
hello321 only alpha:False
321l123 is number or alpha:True
321123 only number:True
321123 is number:False
False
True
True
一个小游戏:

while True:    print('Enter your age:')    age = input()    if age.isdecimal():        break    print('Please enter a number for your age.')while True:    print('Select a new password (letters and numbers only and more than six words):')    password = input()    if password.isalnum():        if len(password) < 10:            continue        break    print('Passwords can only have letters and numbers.')

用 rjust()、 ljust()和 center()方法对齐文本 :

>>> "hello".ljust(10)
'hello     '
>>> "hello".rjust(10)
'     hello'
>>> "hello".center(10)
'  hello   '

>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------'

小游戏:

def printPicnic(itemsDict, leftWidth, rightWidth):    print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))    for k, v in itemsDict.items():        print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}printPicnic(picnicItems, 12, 5)printPicnic(picnicItems, 20, 6)
---PICNIC ITEMS--
sandwiches..    4
apples......   12
cups........    4
cookies..... 8000
-------PICNIC ITEMS-------
sandwiches..........     4
apples..............    12
cups................     4
cookies.............  8000

用 strip()、 rstrip()和 lstrip()删除空白字符:

>>> spam = ' Hello World '
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
' Hello World'

strip()可以带参数,如果带了参数就将存在的参数删除

>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'

用 pyperclip 模块拷贝粘贴字符串 :

>>> import pyperclip
>>> pyperclip.copy('Hello world!')
>>> pyperclip.paste()
'Hello world!'
 这个函数是调用系统的粘贴板,只要系统粘贴板中有内容即可粘贴

项目:口令保管箱
你可能在许多不同网站上拥有账号, 每个账号使用相同的口令是个坏习惯。如果这些网站中任何一个有安全漏洞, 黑客就会知道你所有的其他账号的口令。最好是在你的计算机上, 使用口令管理器软件, 利用一个主控口令, 解锁口令管理器。然后将某个账户口令拷贝到剪贴板, 再将它粘贴到网站的口令输入框。

#! python3# pw.py - An insecure password locker program.PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6','blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt','luggage': '12345'}import sys, pyperclipif len(sys.argv) < 2:    print('Usage: py pw.py [account] - copy account password')    sys.exit()account = sys.argv[1] # first command line arg is the account nameif account in PASSWORDS:    pyperclip.copy(PASSWORDS[account])    print('Password for ' + account + ' copied to clipboard.')else:    print('There is no account named ' + account)
项目没怎么看懂,后面遇到再来弄,主要是新建.bat批处理文件还有配置环境变量,从dos窗口执行.py文件,绕来绕去把我给弄迷糊了。

Python中 sys.argv[]的用法简明解释


项目: 在 Wiki 标记中添加无序列表 

你希望 bulletPointAdder.py程序完成下列事情:
1. 从剪贴板粘贴文本;
2.对它做一些处理;
3.将新的文本复制到剪贴板

import pyperclippyperclip.copy("Lists of animals\nLists of aquarium life\nLists of biologists by author abbreviation\nLists of cultivars\nof each line of text on the clipboard.")text = pyperclip.paste()# Separate lines and add stars.lines = text.split('\n')for i in range(len(lines)): # loop through all indexes for "lines" list    lines[i] = '* ' + lines[i] # add star to each string in "lines" listtext = '\n'.join(lines)#pyperclip.copy(text)print(text)
实践项目
作为实践,编程完成下列任务。
表格打印
编写一个名为 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 maxlen(tableData):    onelist = [0] * (len(tableData[0]))    # 总共列数    for i in range(len(tableData[0])):        # 获取行数        for j in range(len(tableData)):            # 将列的最大值放入列表            if onelist[i] < len(tableData[j][i]):                onelist[i] = len(tableData[j][i])    # 返回列表    return onelist# 打印方法def print_table(tableData):    max_list_row = maxlen(tableData)    for i in range(len(tableData)):        for j in range(len(max_list_row)):            print(tableData[i][j].ljust(max_list_row[j]+4),end="")        print()print_table(tableData)
apples    oranges    cherries    banana    Alice     Bob        Carol       David     dogs      cats       moose       goose 
最后这个实践项目弄得比较久,可能是因为自己进度太快所导致。不过我有其他语言的基础,做起来也不是太费力气,总的来说还是不错的。

最后在做这个项目的时候我就在想,是否可以自己写一个方法,可以检测出list是否存在list,再把打印方法给完善一下,使其能打印长度不一样的二维list甚至是三维的。