python 字符串+字典

字符串

字符串不可改变

format = "hello, %s,%s enough for you?"
values = ('world','Hot')
format % values
'Hello,world.Hot enough for you?'
"{},{} and {}".format("first","second","third")
"first,second and third"
"{3} {0} {2} {1} {3} {0}".format("be","not","or","to")
"to be or not to be"
from math import pi
"{name} is approximately {value:.2f}.".format(value=pi,name="pi")
'pi is approximately 3.14.'
from math import e
f"Euler's constant is roughly {e}."
'Euler's constant is roughly 2.718287825459045'

"Euler's constant is roughly {e}.".format(e=e)
'Euler's constant is roughly 2.718287825459045'

字符串格式设置

字段名替换

索引或标识

"{foo} {1} {bar} {0}".format(1,2,bar=4,foo=3)

基本转换

>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π")) 
π 'π' '\u03c0'

在这里插入图片描述

"The number is {num:b}".format(num=42) 
'The number is 101010'

宽度、精度、千位分隔

"{num:10}".format(num=3)
          3
"{name:10}".format(name='Bob')
'Bob'                         //数与字符对齐方式不同
{pi:10.2f}".format(pi=pi) 
'      3.14'
"{:.5}".format("Guido van Rossum") 
'Guido'
One googol is {:,}'.format(10**100)
'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,00 0,000,000,000,000,000,000,000,000,000,000,000,000,000,000'

符号、对齐和0填充

"{:010.2f}".format(pi)
'0000003.14'

//左对齐、右对齐、居中
print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14      
   3.14   
      3.14

字符串方法

center
"The Middle by Jimmy Eat world".enter(39)
'  The Middle by Jimmy Eat world  '
"The Middle by Jimmy Eat world".enter(39,'+')
'++++The Middle by Jimmy Eat world++++'
find
title = "Monty Python's Flying Circus"  //找不到返回-1
title.find('Monty')
0
title.find('Python')
6
tar = "$$$ Get rich now!!! $$$"
tar.find('$$$',0,16)
-1
join
seq = [1,2,3,4,5]
sep = '+'
sep.join(seq)   //error
seq = ['1','2','3']
seq.join(sep)
'1+2+3'
dir = '','user','bin','env'
'/'.join(dir)
'/user/bin/env'
lower
"BIG".lower()
'big'
"that's another".title()
'That's Another'
replace
"This is test".replace('is','eez')
'Theez eez a test'
split
'1+2+3+4+5'.split('+')
['1','2','3','4','5']
'Using the default'.split()
['Using','the','default']
strip
'   internal whitespace is kept   '.strip()
'internal whitespace is kept'   //只能删除两端的空格
translate

同时替换多个字符,效率比replace高

需要先建立转换表

table = str.maketrans('cs', 'kz')  //c——>k   s——>z
'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'  

t = str.maketrans('s','z',' ')   //此处为删除空格
'this is test do you'.translate(t)  
'thizizteztdoyou'
判断类字符方法

一般以is开头

isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、 isprintable、isspace、istitle、isupper。

字典

python中唯一的一种映射类型

创建

phonebook={'Ben':'122',"weillian":'120','wang':'2560'}
//键:值  
dict
item = [('name','Bentli'),('age',42)]
d = dict(item)
{'name': 'Bentli', 'age': 42}
d = dict(name='ben',age=42)
{'name':'ben','age':42}
基本操作
len(d)  返回项数
d[k] 返回k关联的值
d[k] = v  值关联到k
del d[k]  删除键为k的项
k in d 检查是否包含键维k的项
x = {}
x[42] = 'fool'
{42:'fool'}
字典方法

clear()

d = {}
d['name'] = 'Gumby'
d['age']=18
d.clear()
{}
x = {}
y = x
x['name']='ben'
y
{'name':'ben'}
x.clear()   //此时y也会清除 反之依然
y
{}

copy

x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()
y['username'] = 'mlh'    //替换后  原件x不会被改变
y['machines'].remove('bar')   //修改后 原件x也改变
{'username': 'mlh', 'machines': ['foo', 'baz']}
{'username': 'admin', 'machines': ['foo', 'baz']}
from copy import deepcopy   //深复制 避免以上问题

fromkeys

{}.fromkeys(['name','age'])
{'name': None, 'age': None}
dict.fromkeys(['name', 'age'], '(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}

get

d ={}
print(d.get('name'))  //d中不存在 返回None
None
d.get('name','N/A')     //指定返回值

items

d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
d.items()   //返回字典视图(用于迭代)
dict_items([('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')])

list(d.items())
[('spam', 0), ('title', 'Python Web Site'), ('url', 'http://www.python.org')]

keys

d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
d.keys()
dict_keys(['title', 'url', 'spam'])  //字典视图

pop

d = {'x':1,'y':2,'z':3}
x.pop('x')
{'y',2,'z',3}

popitem

d = {'x':1,'y':2,'z':3}
d.popitem()  //随机pop一个项

setdefault

d = {}
d.setdefault('name', 'N/A')  //d中无'name' 创建{'name':'N/A'}
s={'name':GGB}
s.setdefault('name','A/N')  //s中有'name'   返回已存在的值

update

//对于通过参数提供的字典,将其项添加到当前字典中。如果当前字典包含键相同的项,就替换它
x = {'name':'wang','age':18,'sex':'man'}
y = {'age':24}
x.update(y)
x
{'name': 'wang', 'age': 24, 'sex': 'man'}

values

x = {'name':'wang','age':18,'sex':'man'}
x.values()
dict_values(['wang', 18, 'man'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值