1、空类型
空类型判断:Python中关于空类型的判断使用的内建函数any()
在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。
python变量初始化为空值的方式分别是:
数值
digital_value = 0
字符串
str_value = ""
列表
list_value = []
字典
ditc_value = {}
元组
tuple_value = ()
2、字典
判断某个键是否存在于字典中,有如下方式:
1)dict.get(key,None) #没有键的话返回None,可通过这种方式判断
2)if key in dict:
创建字典的方式
#创建一个空字典
empty_dict = dict()
print(empty_dict)
#用**kwargs可变参数传入关键字创建字典
a = dict(one=1,two=2,three=3)
print(a)
#传入可迭代对象
b = dict(zip(['one','two','three'],[1,2,3]))
print(list(zip(['one','two','three'],[1,2,3])))
print(b)
#传入可迭代对象
c = dict([('one', 1), ('two', 2), ('three', 3)])
print(c)
c1 = dict([('one', 1), ('two', 2), ('three', 3),('three', 4),('three', 5)])
print(c1)#如果键有重复,其值为最后重复项的值。
#传入映射对象,字典创建字典
d = dict({'one': 1, 'two': 2, 'three': 3})
print(d)
print(a == b == c == d)
输出:
{}
{'one': 1, 'two': 2, 'three': 3}
[('one', 1), ('two', 2), ('three', 3)]
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 5}
{'one': 1, 'two': 2, 'three': 3}
True
3、拼接字符串的方式
常用的有7种
1)使用 % 占位拼接
print('%s %s' % ('Hello','World'))
以上代码会输出Hello World。
这种方式第一次出现是在C语言中,%s是一个占位,意味着这里可以被放置一个字符串,实际的字符串的值通过后面的元组传递。占位符不仅仅有%s,如%d代表一个整数、%f代表浮点数等等。
这种方式最大的缺点就是每个不同类型的数据需要使用不同的占位符,略显麻烦。
2)使用 format() 方法
format()方法使用{}来做占位,使用方式有3种。
- 第一种
# format函数的参数按照{}从前往后的顺序一一对应值
s = 'Hello {},Hello {}'.format('World','Python')
- 第二种
# {}中填入索引值,{0}代表值 'World',以此类推,这样就可以在任意位置传入任意值
s = 'Hello {0},Hello {1}'.format('World','Python')
- 第三种
# {}填入属性名,参数通过key-value形式传入值
s = 'Hello {name1},Hello {name2}'.format(name1='World',name2='Python')
3)使用 ()的方式
这种方式咋一看起来很像元组的形式,但实际并不是,其中不能使用逗号作为字符的分隔符(而元组是用逗号作为各元素的分隔符的),只能是空格。
s = ('Hello' ',' 'World')
print(s)
输出结果是Hello,World,这种方式每一对引号为一部分,相邻引号对之间可以使用任意多个空格分开。并且,这种方式得到的字符串的数据类型就是str。
这种方式的缺点是,()内不能使用变量,如果有变量,就不能有其他字符串常量,并且,变量最多也只能有一个。即s = (str1),str1是变量,这样是合理的。s = (str1 str2)和s = (str1 'Hello')都是不行的,会报错。
4)使用模板Template
模板拼接字符串是一种完全的面向对象的方式,贯彻落实了Python一切皆对象的思想。
from string import Template # 导入string模板
s = Template('${s1} ${s2}!!') # ${}是占位符,取对应名字的变量的值,而后与其他字符串拼接
print(s.safe_substitute(s1='Hello',s2='World'))
5)+方式
这在任何语言中,都是最常用的方式。不多说,先上代码。
str1 = 'Hello' + ','
str2 = 'World'
print(str1 + str2)
输出Hello,World。
普遍认为,这种方式的性能较好。的确,这种方式,在大部分情况下,性能都是挺好的。但是如果遇到长字符串的拼接,这种方式的性能就会有明显下降。
6. join()方法拼接
str_list = ['Hello','World']
str_join1 = ' '.join(str_list)
str_join2 = '-'.join(str_list)
print(str_join1) # 输出 Hello World
print(str_join2) # 输出 Hello-World
str对象自带的join()方法接收一个序列参数。而后设置统一的间隔符。普遍来说,拼接长度不超过20时,这种方式效率是最高的。
7) f-string方式
name = 'World'
myname = 'Python_Cat'
words = f'Hello {name},My Name is {myname}.'
print(words) # 输出 Hello World,My Name is Python_Cat.
这种方式在Python3.6版本引入的,{}包裹变量名。这种方式比起format()的可读性要好很多,处理长字符串时,速度与join()相当。
选择原则:对列表结构的拼接,自然是使用join()、对于较短字符串(一般指20以下)使用+的性能最好,超过20的最好使用f-string,如果版本比较低不支持,那就使用format()或者join()。
来源:CSDN
作者:qq_33590958
链接:https://blog.csdn.net/qq_33590958/article/details/102602828