【Class 29】《Python编程快速上手》 查缺补漏三 第五章 字典和结构化数据 第六章 字符串操作

第五章 字典和结构化数据

1. 尝试访问字典中不存在得键,将导致 KeyError 出错信息

>>> spam = {'name': 'Zophie', 'age': 7}
>>> spam['a']
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    spam['a']
KeyError: 'a'
>>> 

2. 字典的方法
spam.keys() 以列表的形式返回所有键值,但他们不能被修改,没有append方法
spam.values() 以列表的形式返回所有数值
spam.items() 返回 键值:数值

>>> spam.keys()
dict_keys(['name', 'age'])
>>> type(spam.keys())
<class 'dict_keys'>

>>> spam.items()
dict_items([('name', 'Zophie'), ('age', 7)])

3. get( ‘key’, defalult_value ) 方法: 要取得key键的值,如果该键不存在时,返回的default_value。

>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'

4. setdefault( ‘key’, defalult_value ) 方法 如果键值存在则返回键对应得值,如果不存在,则返回default_value
你常常需要为字典中某个键设置一个默认值,当该键没有任何值时使用它。代码看起来像这样:

spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
 	spam['color'] = 'black'

setdefault( ) 方法提供了一种方式,在一行中完成这件事。传递给该方法的第一个参数,是要检查的键。
第二个参数,是如果该键不存在时要设置的值。如果该键确实存在,方法就会返回键的值。

>>> spam = {'name': 'Pooka', 'age': 5}
>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}

5. 漂亮打印
如果程序中导入 pprint 模块,就可以使用 pprint()和 pformat()函数,它们将“漂亮打印”一个字典的字。如

import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
 	count.setdefault(character, 0)
 	count[character] = count[character] + 1
pprint.pprint(count) 

输出结果为:
{' ': 13,
',': 1,
'.': 1,
'A': 1,
'I': 1,
'a': 4,
'b': 1,
'c': 3,
'd': 3,
'e': 5,
'g': 2,
'h': 3,
'i': 6,
'k': 2,
'l': 3,
'n': 4,
'o': 2,
'p': 1,
'r': 5,
's': 3,
't': 6,
'w': 2,
'y': 1}

pprint.pprint(someDictionaryValue)
print(pprint.pformat(someDictionaryValue))

>>> import pprint
>>> spam = {'name': 'Zophie', 'age': 7}
>>> pprint.pprint(spam)
{'age': 7, 'name': 'Zophie'}
>>> print(pprint.pformat(spam))
{'age': 7, 'name': 'Zophie'}
>>> 
  1. 嵌套的字典和列表

第六章 字符串操作

1. 原始字符串 r’xxxxxx’
可以在字符串开始的引号之前加上 r,使它成为原始字符串。“原始字符串”完全忽略所有的转义字符,打印出字符串中所有的倒斜杠。

2. 用三重引号得多行字符串

print('''Dear Alice,

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

Sincerely,

Bob''')
  1. 字符串方法
    upper()和 lower()字符串方法返回一个新字符串,其中原字符串的所有字母都被相应地转换为大写或小写。字符串中非字母字符保持不变。
>>> spam = 'Hello world!'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD!'
>>> spam = spam.lower()
>>> spam
'hello world!'

如果字符串至少有一个字母,并且所有字母都是大写或小写,isupper()和islower()方法就会相应地返回布尔值 True。否则,该方法返回 False。

>>> spam = 'Hello world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False

isalpha() 返回 True,如果字符串只包含字母,并且非空
isalnum() 返回 True,如果字符串只包含字母和数字,并且非空;
isdecimal() 返回 True,如果字符串只包含数字字符,并且非空
isspace() 返回 True,如果字符串只包含空格、制表符和换行,并且非空;
istitle() 返回 True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。

>>> '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() 方法返回 True,如果它们所调用的字符串以该方法传入的字符串开始或结束。

>>> 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!') 
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'abc123'.endswith('12')
False
>>> 'Hello world!'.startswith('Hello world!')
True
>>> 'Hello world!'.endswith('Hello world!')
True

join() 如果有一个字符串列表,需要将它们连接起来,成为一个单独的字符串,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']

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

>>> '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()删除空白字符
有时候你希望删除字符串左边、右边或两边的空白字符(空格、制表符和换行符)。
strip()字符串方法将返回一个新的字符串,它的开头或末尾都没有空白字符
lstrip()和 rstrip()方法将相应删除左边或右边的空白字符。

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

用 pyperclip 模块拷贝粘贴字符串

pyperclip 模块有 copy()和 paste()函数,可以向计算机的剪贴板发送文本,或从它接收文本。

导入模块前先安装模块:

C:\Users\Administrator>pip install pyperclip
Collecting pyperclip
  Downloading https://files.pythonhosted.org/packages/2d/0f/4eda562dffd085945d57c2d9a5da745cfb5228c02bc90f2c74bbac746243/pyperclip-1.7.0.tar.gz
Installing collected packages: pyperclip
  Running setup.py install for pyperclip ... done
Successfully installed pyperclip-1.7.0

C:\Users\Administrator>

代码如下:

import pyperclip
print(pyperclip.paste())                         	#  打印鼠标右键复制的内容
pyperclip.copy("copy xxxxxx ")				# 将"copy xxxxxx " 放入剪贴板中, 
print(pyperclip.paste())                         	#  打印鼠标右键复制的内容

运行结果如下:
PS C:\Users\Administrator\Desktop\tmp> python .\Untitled-1.py
# 运行程序前,先 使用鼠标 右键 复制一些东西
PS C:\Users\Administrator\Desktop\tmp>

猜你喜欢

转载自blog.csdn.net/Ciellee/article/details/88073079