python学习-day8

python学习-day8

1、字符串补充学习

1.1、字符串startswith()和endswith()方法:

startswith():检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

语法:str.startswith(substr, beg=0,end=len(string));

strs = 'I Love Python 123'
print(strs.startswith('I', 0, len(strs)))
#输出:True

endswith():判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 “start” 与 “end” 为检索字符串的开始与结束位置。

语法:str.endswith(suffix[, start[, end]])

strs = 'I Love Python 123'
print(strs.endswith('123', 0, len(strs)))
#输出:True

1.2、字符串方法join()和split()

join():将序列中的元素以指定的字符连接生成一个新的字符串。

语法:str.join(sequence)
返回通过指定字符连接序列中元素后生成的新字符串

list1 = ['I', 'Love', 'Python']
print(' '.join(list1))
#输出:I Love Python

split():通过指定分隔符分割字符串,如果指定了num,则返回num + 1个字符串组成的列表

语法:str.split(str=“”, num=string.count(str))
默认为所有的空字符,包括空格、换行(\n)、制表符(\t)
返回分割后的字符串列表

url = "https://www.baidu.com"
print(url.split('.'))
print(url.split('.', maxsplit=1))
#输出:
['https://www', 'baidu', 'com']
['https://www', 'baidu.com']

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

rjust():右对齐

语法:str.rjust(width[, fillchar])
返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串
#右边对齐

str1 = 'i love python'
print(str1.rjust(20, '*'))
#输出:*******i love python

ljust():左对齐

str1 = 'i love python'
print(str1.ljust(20, '*'))
#输出:i love python*******

语法:str.ljust(width[, fillchar])
返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

center():居中对齐

语法:str.center(width[, fillchar])
返回一个指定的宽度 width 居中的字符串,如果 width 小于字符串宽度直接返回字符串,否则使用 fillchar 去填充。

str1 = 'i love python'
print(str1.center(50, '*'))
#输出:******************i love python*******************

示例:

def printPicnic(itemDict, leftWidth, rightWidth):
	#标题居中对齐
    print("PICNIC ITEMS".center(leftWidth + rightWidth, '-'))
    for k, v in itemDict.items():
    	#键左对齐,值右对齐
        print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth, '-'))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)

#输出:
---PICNIC ITEMS--
sandwiches..----4
apples......---12
cups........----4
cookies.....-8000

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

lstrip():删除字符串左边空白字符

语法:str.lstrip([chars])
返回截掉字符串左边的空格或指定字符后生成的新字符串。

str1 = '  i love python  '
str2 = 'www123I Love Python123www'
print(str1.lstrip())
print(str2.lstrip('w123'))
#输出:
i love python  
I Love Python123www

rstrip():删除字符串右边空白字符

语法:str.rstrip([chars])
返回删除 string 字符串末尾的指定字符后生成的新字符串

str1 = '  i love python  '
str2 = 'www123I Love Python123www'
print(str1.rstrip())
print(str2.rstrip('w123'))
#输出:
  i love python
www123I Love Python

strip():删除字符串左、右两边空白字符

语法:str.strip([chars])
返回移除字符串头尾指定的字符序列生成的新字符串。

str1 = '  i love python  '
str2 = 'www123I Love Python123www'
print(str1.strip())
print(str2.strip('w123'))

#输出:
i love python
I Love Python

1.5、pyperclip模块拷贝粘贴字符串

pyprclip模块有copy()和paste()函数
注意:pyperclip模块并非python自带,要安装后才能使用。

pip3 install pyperclip

import pyperclip
项目:口令保管箱

介绍:保管多个账号密码,通过主口令进入保管箱,拷贝账号信息。
1、程序设计及数据结构
采用字典保存账号和口令
from pyperclip import copy, paste
import sys

#! python3
#passwd.py--保存账号和密码
passwd = {
    'email': '[email protected]',
    'blog': '123abc',
    'luggage': '12345'
}

#处理命令行参数
if len(sys.argv) < 2:
    #用法:python passwd.py 参数account
    print('Usage:python passwd.py [account] - copy account password')
    sys.exit()
account = sys.argv[1]

#3、复制正确的口令
if account in passwd:
    copy(passwd[account])
    print('Password for' + account + 'copy the clipboard')
else:
    print('There is no account named' + account)

#运行命令:python day8.py luggage

python学习-day8_第1张图片

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

介绍:在每一行开始处输入星号,一行接一行。
如:
Lists of animals
Lists of aquarium life
Lists of blologists by author abbreviation
Lists of cultivars
运行bulletPointAdder.py程序,剪切板中就包含下面的内容:

  • Lists of animals
  • Lists of aquarium life
  • Lists of blologists by author abbreviation
  • Lists of cultivars
#! python3
# bulletPointAdder.py -Adds Wikipedia bullet points to the start
# of each line of text on the clipboard

import pyperclip
#text得到的是带有\n的字符串
text = pyperclip.paste()
print(text)

# TODO : Separate lines and add starts.
lines = text.split('\n')
for i in range(len(lines)):
    lines[i] = '* ' + lines[i]

#拼接字符串
text = '\n'.join(lines)

pyperclip.copy(text)

1.6、实践操作

1、表格打印
编一个printTable()函数,它接受列表的列表,将它显示在表格中,每列右对齐,列如:
totalData = [
[‘apples’, ‘oranges’, ‘cherries’, ‘banana’],
[‘Alice’, ‘Bob’, ‘Carol’, ‘David’],
[‘dogs’, ‘cats’, ‘moose’, ‘goose’]
]
打印如下:
apples Alice dogs

oranges Bob cats

cherries Carol moose

banana David goose

totalData = [
    ['apples', 'oranges', 'cherries', 'banana'],
    ['Alice', 'Bob', 'Carol', 'David'],
    ['dogs', 'cats', 'moose', 'goose']
]

def printTable(lst):
    rows = len(lst[0])
    columns = len(lst)
    colWidth = [0] * len(lst)
    #获取每列的最长字符串为多少
    for c in range(columns):
        for r in range(rows):
            if colWidth[c] < len(lst[c][r]):
                colWidth[c] = len(lst[c][r])
                
    #print(colWidth)
    for r in range(rows):
        for c in range(columns):
        	#c每次循环从0开始
            print(lst[c][r].rjust(colWidth[c], '-'), end=' ')
        print('\n')

printTable(totalData)

你可能感兴趣的:(python,学习)