Python编程快速上手第6章字符串操作

转义字符

\'单引号
\"双引号
\t制表符
\n换行符
\\倒斜杠
>>> print("Hello there!\nHow are you?\nI\'m doing fine.")
Hello there!
How are you?
I'm doing fine.

原始字符串

>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.

用三重引号的多行字符串,多行注释

print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')

字符串下标和切片
字符串像列表一样,使用下标和切片。
字符串的 in 和 not in 操作符
这些表达式测试第一个字符串(精确匹配,区分大小写)是否在第二个字符串中。

>>> 'Hello' in 'Hello World'
True
>>> 'Hello' in 'Hello'
True

有用的字符串方法
字符串方法 upper()、lower()、isupper()和 islower()
isX 字符串方法
isalpha()返回 True,如果字符串只包含字母,并且非空;(a-zA-Z)
isalnum()返回 True,如果字符串只包含字母和数字,并且非空;(a-zA-Z0-9)
isdecimal()返回 True,如果字符串只包含数字字符,并且非空;(0-9)
isspace()返回 True,如果字符串只包含空格、制表符和换行,并且非空;(\t\n)
istitle()返回True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。(Hello)

>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()
True
>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> 'This Is Title Case'.istitle()
True
>>> 'This Is Title Case 123'.istitle()
True
>>> 'This Is not Title Case'.istitle()
False
>>> 'This Is NOT Title Case Either'.istitle()
False

字符串方法 startswith()和 endswith()

>>> 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True

字符串方法 join()和 split()
join()方法是针对一个字符串而调用的,并且传入一个列表值

>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'

split()方法做的事情正好相反:它针对一个字符串调
用,返回一个字符串列表。

>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']
#\n按照换行符分割变量中存储的多行字符串,返
#回列表中的每个表项,对应于字符串中的一行。

用 rjust()、ljust()和 center()方法对齐文本
第一个参数是一个整数长度,用于对齐字符串。

>>> 'Hello'.rjust(10)
' Hello'
>>> 'Hello'.rjust(20)
' Hello'
>>> 'Hello World'.rjust(20)
' Hello World'
>>> 'Hello'.ljust(10)
'Hello

二个可选参数将指定一个填充字符,取代空格字符。

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

用 strip()、rstrip()和 lstrip()删除空白字符
空白字符(空格、制表符和换行符)

>>> spam = ' Hello World '
>>> spam.strip()
'Hello World'
------------------------------------------
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'

用 pyperclip 模块拷贝粘贴字符串

>>> import pyperclip
>>> pyperclip.copy('Hello world!')
>>> pyperclip.paste()
'Hello world!'

项目1:口令保管箱
你希望用一个命令行参数来运行这个程序,该参数是账号的名称。例如,账号
的口令将拷贝到剪贴板,这样用户就能将它粘贴到口令输入框。通过这种方式,用
户可以有很长而复杂的口令,又不需要记住它们。

PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
#口令保管箱
import pyperclip
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
print("Please input name:(Enter space to quit)")
while True:
    name = input()
    if name == '':break
    if name in PASSWORDS:
        print("i have your passwd:%s"%(PASSWORDS[name]))
        pyperclip.copy(PASSWORDS[name])
    else:
        print('do not have passwd.')
        passwd = input("input passwd:")
        PASSWORDS.setdefault(name, passwd)
        print('Is saved.')
    print("Please input next name:")
#

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

Lists of animals
Lists of aquarium life
Lists of biologists by author abbreviation
Lists of cultivars

要求:在前面加上*号

'''
Lists of animals
Lists of aquarium life
Lists of biologists by author abbreviation
Lists of cultivars
'''
import pyperclip
wikiText = pyperclip.paste()
wikiList = wikiText.split('\n')
outWiki = []
for i in range(len(wikiList)):
    outWiki.append( '* ' + wikiList[i])
print('\n'.join(outWiki))
pyperclip.copy('\n'.join(outWiki))

项目3:表格打印

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

要求:

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']]
#找出每行最长存入list
maxStr = [0,0,0]
# 列做内层,行做外层
#0,0-0,1-0,2-0,3
for i in range(len(tableData)):
    for j in range(len(tableData[0])):
        if len(tableData[i][j]) > maxStr[i]:
            maxStr[i] = len(tableData[i][j])+1
# 列做外层,行做内层
#0,0-1,0-2,0
for i in range(len(tableData[0])):
    for j in range(len(tableData)):
        print(tableData[j][i].ljust(maxStr[j]),end='')
    print()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值