一、基础操作
1、字符串连接
a = 'hello' + 'python'
a
'hellopython'
2、字符串重复多遍
a*3
'hellopythonhellopythonhellopython'
3、字符串长度
len(a)
11
二、核心操作
1、字符串分割
a = '1 2 3 4 5'
a.split()
['1', '2', '3', '4', '5']
b = '1,2,3,4,5'
b.split(',')
['1', '2', '3', '4', '5']
2、字符串拼接
a_str = ' '
a_str.join(a)
'1 2 3 4 5'
3、字符串替换
a = 'hello python'
a.replace('python','world')
'hello world'
注意:此时如果再输出a依然是hello python,如果想保留变化,就要新命名变量如:
b = a.replace('python','world')
b
'hello world'
4、更改大小写
c = b.upper()
d = c.lower()
c,d
('HELLO WORLD', 'hello world')
5、空格处理
a = ' hello python '
b = a.strip()
c = a.lstrip()
d = a.rstrip()
b,c,d
('hello python', 'hello python ', ' hello python')
strip函数可以去除两边空格,lstrip函数可以去除左边空格,rstrip函数可以去除右边空格
6、顺序
'{} {} {}'.format('a','b','c')
'a b c'
'{2} {1} {0}'.format('a','b','c')
'c b a'
'{a} {b} {c}'.format(a=10,b=20,c=30)
'10 20 30'
a = 'the result is :'
b = 123
c = 456
result = '%s %f %d' %(a,b,c)
result
'the result is : 123.000000 456'