python3.5入门笔记(4) 字符串

转义字符+格式化符号

1、转义字符

(1)print('\'越努力,越幸运\'')

'越努力,越幸运'

(2)print('\'越努力\'\n\'越幸运\'')

'越努力'

'越幸运'

2、格式化符号

 

(1)print('今年%d岁了'%10)

今年10岁了

(2)print('圆周率的值为: %f' % 3.1415)

圆周率的值为: 3.141500

     print('圆周率的值为: %.2f' % 3.1415)

圆周率的值为: 3.14

     print('圆周率的值为: %.2f%%' % 3.1415)  

圆周率的值为: 3.14%

格式化元祖+基本转换符

1、print('今年是%d年,中国%s,获%d金牌'%(2008,'夺冠了',50))

今年是2008年,中国夺冠了,获50金牌

只有元祖和字典可以格式化一个以上的值

2、基本转换说明符

(1) %       转换开始说明

(2) -         左对齐            

    +         转换之前加符号,默认正号

    “”         空白字符       

    0         转换位不够0填充

(3) 宽度  .前面是宽度,如是*,进度从元祖读出

(4) 精度  . 后跟精度值,如是字符,显示最大宽度;如是*,进度从元祖读出

宽度和精度:

print('圆周率的值为: %10.2f%%' % 3.1415)       字符宽度为10,精度为2,两个百分号表示百分百

圆周率的值为:       3.14%       宽度未达到会在前面补空格,类似右对齐,小数点算一位

print('从元祖获取宽度和精度: %*.*s'%(10,5,'helloworld'))     宽度10,精度5

从元祖获取宽度和精度:      hello

0填充:

print('圆周率的值为: %010.2f%%' % 3.1415)

圆周率的值为: 0000003.14%

-对齐:

print('圆周率的值为: %-10.2f%%' % 3.1415)

圆周率的值为: 3.14      %         类似会将右对齐变为左对齐

+号:

print('正号: %+5d' %10 + '\n' + '负号: %+5d' %-10)

正号:   +10

负号:   -10

字符串方法(*)

1find() 检查字符串是否包含字符串,包含返回索引值,否则返回-1

str.find(str,beg=0,end=len(string))

字符串.方法.对象

a='do it now'

a.find('it',0,4)     -1

a.find('it',0,5)      3    

2、join()   连接元素.join.(字符串元祖或列表)

a=('a','v','x','c')

>>> '-'.join(a)       'a-v-x-c'

str = "-";

seq = ("a", "b", "c"); # 字符串序列

print str.join( seq );    ‘a-b-c’

str 代表字符串,sequence代表元素序列

3、low()  大写转小写

test='MAKE'

>>> test.lower()       'make'

field='DO IT NOW'

查询时大写只能用大写查询,小写只能用小写查询

field.lower().find('IT'.lower())           3

4、upper()      小写转大写

test='make'

>>> test.upper()      'MAKE'

5、swapcase()   大写转小写,小写转大学

test='HELLO,world!'

>>> test.swapcase()    'hello,WORLD!'

6、replace()  将部分字符串的内容进行替换(修改)

字符串.replace(‘字符串’,‘新字符串’)

test='one three'

>>> test.replace('three','two three')

'one two three'

7、split()   将字符串分割、切片

(1)test='one two three'

>>> test.split()   ['one', 'two', 'three']   不指定按空格切片

>>>test.split('o')  ['', 'ne tw', ' three']    指定按指定元素切片

(2)name = 'id>>123'

aa=name.split('>>')[0] 切割后左边字符串

bb=name.split('>>')[1] 切割后右边字符串

print(aa)     id

print(bb)    123

8、strip()    移除字符串头、尾指定字符

cs01='abcdaaba'

>>> cs01.strip('a')     'bcdaab'

9、maketrans和translate()用法

str.maketrans(intab, outtab]);  两个参数为长度相同的字符串

intab=’123’

outab=’abc’

str='a是第1个字母‘

trantab=str.maketrans(intab,outab)

>>> trantab   {49: 97, 50: 98, 51: 99}   创建字符映射的转换表(1表示49,a表示97,依次类推)

str.translate(trantab)   'a是第a个字母'   1会变成a

既在intab,又在str的字符,用outab中对应字符替换

发布了28 篇原创文章 · 获赞 1 · 访问量 3193

猜你喜欢

转载自blog.csdn.net/pdd51testing/article/details/83752598