Python学习之字符串,字典

Python学习之字符串,字典

字符串

转换说明符%s

类似于C#中的占位符”{}”

>>> name='hello,%s,%s'
>>> d=('world','python')
>>> name%d
'hello,world,python'

方法format

作用与C#的占位符相同

>>> '{},{},{},{}'.format('a','b','c','d')  #逗号不是必须的
'a,b,c,d'
>>> '{},{},{}'.format('a','b','c','d')  
'a,b,c'
>>> '{2},{2},{2},{2}'.format('a','b','c','d')
'c,c,c,c'
#接下来是错误示范
>>> '{},{},{},{}'.format('a','b','c')
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    '{},{},{},{}'.format('a','b','c')
IndexError: tuple index out of range

f字符串

在Python 3.6中,如果变量与替换字段同名,还可使用一种简写。在这种情况下,可 使用f字符串——在字符串前面加上f。

>>> ap=99
>>> 'this is {ap}'
'this is {ap}'
>>> f'this is {ap}'
'this is 99'

个中区别还是比较好分辨的

字符串方法

center方法

通过在两边添加填充字符(默认为空格)让字符串居中

>>> 'hello,world'.center(30)
'         hello,world          '
>>> 'hello,python'.center(30,'$')
'$$$$$$$$$hello,python$$$$$$$$$'

find方法

在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1

>>> 'hello,world,python'.find('hello')
0
>>> 'hello,world,python'.find('world')
6
>>> 'hello,world,python'.find('py')
12
#find方法还可指定起点与终点
>>> 'hello,world,python'.find('hello',5)
-1
#通过这种方法找到world中的o
>>> 'hello,world,python'.find('o',6,12)
7

join方法

用于合并序列的元素

>>> a=['1','2','3','4,']
>>> '+'.join(a)
'1+2+3+4,'

lower方法

返回字符串的小写版本

>>> 'THanks,Jack'.lower()
'thanks,jack'

replace方法

将指定子串都替换为另一个字符串,并返回替换后的结果

>>> 'Hello,World'.replace('World','Python')
'Hello,Python'

split方法

用于将字符串拆分为序列

>>> a='1+2+3+4'
>>> a.split('+')
['1', '2', '3', '4']
>>> 'hello world python'.split()
['hello', 'world', 'python']

strip方法

将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果

>>> '   asd   '.strip()
'asd'
>>> '   a   s   d    '.strip()
'a   s   d'
#还可在一个字符串参数中指定要删除哪些字符
>>> 'hello world python'.split('o')
['hell', ' w', 'rld pyth', 'n']

translate方法

方法translate与replace一样替换字符串的特定部分,但不同的是它只能进行单字符替换。 这个方法的优势在于能够同时替换多个字符,因此效率比replace高

#将'l'转换成'n',将'h'装换成'e'
>>> table=str.maketrans('lh','ne')
>>> 'hello world python'.translate(table)
'eenno wornd pyteon'

你可能也注意到了,在转换之前我创建了一个转换表,运用了方法maketrans()。这也是使用translate方法所必须做到的

字典

什么是字典

字典是一种映射。字典中有键与值,它们一一对应

字典的代码格式

>>> name={'a':'20','b':'23','c':'21'}
>>> name['a']
'20'

此即创建了一个字典,并使用它进行了查询

创建字典的函数dict

使用函数dict从其他映射(如其他字典)或键值对序列创建字典

>>> name=(['a','b'],['21','23'])
>>> name=dict(name)
>>> name
{'a': 'b', '21': '23'}
>>> name=dict(a=21,b=23)
>>> name
{'a': 21, 'b': 23}

对字典的操作

其基本操作大致与对列表的操作相同,但也有不同点

# 相同点
>>> name={'a':'20','b':'23','c':'21'}
>>> len(name)  #返回键值对数目
3
>>> name['b']  #查询
'23'
>>> name['b']=22  #修改
>>> name['b']
22
>>> del name['b']  #删除
>>> name
{'a': '20', 'c': '21'}
>>> 'b' in name  #查找(是否存在)
False
>>> 'a' in name
True

不同点

#直接进行赋值,若找不到键,则会创建
>>> a={}
>>> a[1]='a'
>>> a
{1: 'a'}
#字符串与字典
>>> a['b']='python'
>>> a
{1: 'a', 'b': 'python'}
>>> "hello,world,{b}".format_map(a)
'hello,world,python'
>>> f"hello,world,{1}".format_map(a)  #注意,这里用了f字符串,不然会报错
'hello,world,1'

字典方法

clear方法

删除所有的字典项

>>> a
{1: 'a', 'b': 'python'}
>>> a.clear()
>>> a
{}

copy方法

返回一个新字典,其包含的键值对与原来的字典相同

>>> name={'a':'20','b':'23','c':'21'}
>>> a=name.copy()
>>> a
{'a': '20', 'b': '23', 'c': '21'}
>>> name.clear()
>>> name
{}
>>> a
{'a': '20', 'b': '23', 'c': '21'}

fromkeys方法

创建一个新字典,其中包含指定的键,且每个键对应的值都是None

>>> a=dict.fromkeys(['name','age'])
>>> a
{'name': None, 'age': None}
#若不想使用默认值,还可使用自定义值
>>> b=dict.fromkeys(['name','age'],('hello'))
>>> b
{'name': 'hello', 'age': 'hello'}

get方法

方法get为访问字典项提供了宽松的环境。通常,如果你试图访问字典中没有的项,将引发错误

>>> b
{'name': 'hello', 'age': 'hello'}
>>> b.get('name')
'hello'
>>> b.get(1,'none')   #意思为,若没有找到1,则返回none
'none'

items方法

方法items返回一个包含所有字典项的列表,其中每个元素都为(key, value)的形式。字典项 在列表中的排列顺序不确定

>>> b
{'name': 'hello', 'age': 'hello'}
>>> b.items()
dict_items([('name', 'hello'), ('age', 'hello')])

keys方法

方法keys返回一个字典视图,其中包含指定字典中的键

>>> b
{'name': 'hello', 'age': 'hello'}
>>> b.keys()
dict_keys(['name', 'age'])

pop方法

方法pop可用于获取与指定键相关联的值,并将该键值对从字典中删除

>>>b
{'name': 'hello', 'age': 'hello'}
>>> b.pop('name')
'hello'
>>> b
{'age': 'hello'}

setdefault方法

方法setdefault有点像get,因为它也获取与指定键相关联的值,但除此之外,setdefault 还在字典不包含指定的键时,在字典中添加指定的键值对。

>>> b
{'age': 'hello'}
>>> b.setdefault('name','none')
'none'
>>> b
{'age': 'hello', 'name': 'none'}

update方法

使用一个字典中的项来更新另一个字典

>>> b
{'age': 'hello', 'name': 'none'}
>>> a={'name':'a'}
>>> b.update(a)
>>> b
{'age': 'hello', 'name': 'a'}

values方法

返回一个由字典中的值组成的字典视图。不同于方法keys,方法values返回的视 图可能包含重复的值

>>> b
{'age': 'hello', 'name': 'a'}
>>> b.values()
dict_values(['hello', 'a'])

Go to the top

发布了19 篇原创文章 · 获赞 3 · 访问量 6900

猜你喜欢

转载自blog.csdn.net/weixin_42132384/article/details/81591291