1、函数isdigit(),判断字符串是否是数字
a='aAsmr3idd4bgs7Dlsf93AF'
is_digit=[]
for x in a:
if x.isdigit():
is_digit.append(x)
print(is_digit)
['3', '4', '7', '9', '3']
2、函数join(),可以让将字符串、元祖、列表中的元素以指定的字符连接成新的字符串。
'sep'.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
a='aAsmr3idd4bgs7Dlsf93AF'
is_digit=[]
for x in a:
if x.isdigit():
is_digit.append(x)
print(''.join(is_digit))
34793
#或者可以用‘/’隔开
a='aAsmr3idd4bgs7Dlsf93AF'
is_digit=[]
for x in a:
if x.isdigit():
is_digit.append(x)
print('/'.join(is_digit))
3/4/7/9/3
#字符串的连接还可以用“+=”符号
a='aAsmr3idd4bgs7Dlsf93AF'
is_digit=[]
for x in a:
if x.isdigit():
is_digit+=x
print(is_digit)
['3', '4', '7', '9', '3']3、函数set(),set是一个无序且不重复的元素集合。其中重复的字符都只出现一次。
函数list(),列表。
函数dict(),字典
dict(a='a', b='b', t='t') {'a': 'a', 'b': 'b', 't': 't'}
4、带步进的切片
- seq[start:end:step]
- # 开始索引,结束索引,步长
- # 含左不含右
1.带步进正向切片
默认步进为1
- In[24]: a = '123456789'
- In[25]: a[0:8]
- Out[25]:
- '12345678'
指定步进
- In[26]: a[0:8:2]
- Out[26]:
- '1357'
带步进遍历
- In[33]: a[::2]
- Out[33]:
- '13579'
2.带步进反向切片
- In[27]: b = [12,34,56,78,90]
- In[34]: b[::-1]
- Out[34]:
- [90, 78, 56, 34, 12]
- In[35]: b[::-2]
- Out[35]:
- [90, 56, 12]
5、函数items(),Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
6、在字典中,根据值来搜索对应的键
a={'a':'haha','b':'xixi','c':'enen','d':'haha'} s='haha' key_list=[] for x,y in a.items(): if y==s: key_list.append(x) print(key_list)
['a', 'd']
7、在字符串中剔除数字
a='advhiHF213' a=[x for x in a if not x.isdigit()] print(''.join(a))
advhiHF
8、sorted(iterable, cmp=None, key=None, reverse=False)
cmp:用于比较的函数,比较什么由key决定;
key:用列表元素的某个属性或函数进行作为关键字,有默认值,迭代集合中的一项;
reverse:排序规则. reverse = True 降序 或者 reverse = False 升序,有默认值。
返回值:是一个经过排序的可迭代类型,与iterable一样。
a='advhiHF213' a=[x for x in a if not x.isdigit()] b=sorted(a) print(b)
['F', 'H', 'a', 'd', 'h', 'i', 'v']
a='advhiHF213' a=[x for x in a if not x.isdigit()] b=sorted(a,key=str.upper) print(b)
['a', 'd', 'F', 'h', 'H', 'i', 'v']
8、函数replace(),替换
a='I am lilei' print(a.replace('lilei','hanmeimei'))
I am hanmeimei
9、函数translate(),翻译表,多个对应的字符替换,注意与replace()的区别,replace是对应的字符串替换,而translate是对应的单个字符逐个替换
g=str.maketrans('123','abc') a='123456321213' b=a.translate(g) print(b)abc456cbabac
10、with的应用
g=open('a.txt','w')
g.write('hahaha')
g.close()
#等同于
with open('a.txt','w') as g
g.write('hahaha')
11、函数__doc__, '''显示注释'''
def test(): '''哈哈哈''' return 4 print(test.__doc__)
哈哈哈
12、global 将变量定义为全局变量,可以通过定义为全局变量实现在函数内部改变变量值。
x=6
def func(): global x print( 'x is ', x) x = 2 print('Change local x to ', x) func() print(x)x is 6
Change local x to 2
2
13、**代表字典,*代表元组
def test(**d): return d print(test(a=1,b=2,c=3))
{'a': 1, 'b': 2, 'c': 3}
def test(*fd): return fd print(test(1,2,3,'a',4,(1,2),[1,4]))
(1, 2, 3, 'a', 4, (1, 2), [1, 4])