字符串格式化:
字符串格式化有两种:% format
1. %格式化字符串
- %s 使用str()函数进行字符串转换
- %d 转为十进制整数
- %f 转为浮点数
'hello %s ' %('wanzi') 'hello wanzi' '%f' % (3.14) #改为小数点后三位:'%.3f' %(3.14) '3.140000' #默认保留小数点后六位 # 3.141 '%d' % (3) 3
2. format格式化字符串
- 'hello{}'.format('world')
- '{1},{2},{3},{4}'.format('hello''world')
- '{first},{second},{first}'.format(first='hello',second='world')
'hello{}'.format('world')
'hello world'
'i am from {country},i {age} now'.format(country='Chain',age=18)
我来自中国,今年18岁
'hello{}{}'.format('蜡笔小新','樱桃小丸子')
你好,蜡笔小新,樱桃小丸子
strip()
格式:
'xxxxxxxx'.strip( [chars])
用法:
- chars为空,默认去除头尾空白符(包括/n /r /t '' ,即:换行,回车,制表符,空格)
- chars不为空,函数会将chars拆成一个一个字符,去除头尾指定的字符
# 头尾开始剔除指定字符,直到遇到非匹配字符时便停止
# 返回的是去除头尾字符(或空白符)的string副本,string本身不会发生变化
当chars为空时:
'labixiaoxin '.strip()'labixiaoxin' '/n 蜡笔小新 '.strip() '蜡笔小新'
当chars不为空时:
'123abcd123'.strip('12')'3abc123' #头尾开始去除chars位置的数字,遇到不符合的字符时便会停止
判断字符串开头结尾字符:
'x'.startwith('L') # 判断字符串是否以L开头
'x'.endtwith('K') # 判断字符串是否以k结尾
'labixiaoxin'.startswith('l')
ture # 字符串以字母l开头返回正确ture
'yingtaoxiaowanzi'.endswith('z')
False # 字符串不是以字母i结尾返回正确False
判断字符串开头结尾字符:
'x'.find('d') 找到这个字符返回下标,多个时返回第一个;不存在的字符返回-1
'x'.index('a') 找到这个字符返回下标,多个时返回第一个;不存在的字符报错
字符串替换:
'aca'.replace(c,bbb) # 将aca中的c换成bbb\