目录
convert int to str
int str list 的关系:
int - str 互转直接用 int(),str()
int - list 不能互转 用 int——str——list:
str to list:
1.convert str to list of character
a = '1234234'
print(list(a)) #list()
>>>
['1', '2', '3', '4', '2', '3', '4']
2.split()
str.split(sep, maxsplit)
a= '1234234'
print(a.split('2')) #删除了‘分隔符’:‘2’
>>>
['1', '34', '34']
print(a.split('2',1)) #仅进行‘1’次分隔
>>>
['1', '34234']
a= 'hello world[www.sblife.com]python'
#输出url
print(a.split('[')[1].split(']')[0])
>>>
www.sblife.com
a= 'Hello World!'
print(a.split()) #自动以空格为分隔符
>>>
['Hello', 'World!']
list to str
join()
''.join(lsit), list 里数据类型要为 ‘str’
a= ['Hello Word!','2']
ret = '--'.join(a) #用‘’内的 将list中的元素 连起来
print(ret)
>>>
Hello Word!--2
a= [1,2,3,4] #a中数据为 int
b= [str(i) for i in a] #list中元素数据类项变成 str
ret = int(''.join(b)) #convert list to str to int
print(ret - 1234)
>>>
0
切片
str[start_index:end_index:sep]
这种索引使得可以按‘任意顺序’来使用 list 和 str
a= [1,2,3,4] #list
b= '1234' #str
print(a[::-1]) #sep<0, 反向索引
print(b[::-1])
print(b[::-2]) #间隔为‘2’索引
>>>
[4, 3, 2, 1]
4321
42
一行代码实现reverse
return int(str(x)[::-1] if x>=0 else f'-{str(-x)[::-1]}')
其中
1.f'part_1{part_2}' 为强制格式化 part_2为变化内容,part_1为不变
name = 'Eric'
age = 74
print(f'Hello, {name}. You are {age}.')
>>>
'Hello, Eric. You are 74.'
2.注意 if-else 的格式
divmod()
divmod(x, y) return((x-x%y)/y, x%y)
t, v = divmod(9, 2)
print(t, v)
>>>
4 1
储存函数正负的技巧
s, t = (1, x) if x>=0 else s, t = (-1, -x)
# s储存符号 x储存数字