Python字符串之进阶篇

一 字符串的索引和分片

1、介绍
在Python中的字符串中,字符序号是以0开始的,另外最后一个字符的序号为-1。
2、举例
  1. >>> str ='abcdefg'
  2. >>> str[2]
  3. 'c'
  4. >>> str[-2]
  5. 'f'
  6. >>> str[-0]
  7. 'a'
  8. >>> str[-1]
  9. 'g'
  10. >>> str[1:4]
  11. 'bcd'
  12. >>> str[1:1]
  13. ''
  14. >>> str[2:4]
  15. 'cd'
  16. >>> str[1:-1]
  17. 'bcdef'
  18. >>> str[0:-2]
  19. 'abcde'
  20. >>> str[:-2]
  21. 'abcde'
 
二 格式化字符串
1、格式化符号
    符   号 描述
      %c  格式化字符及其ASCII码
      %s  格式化字符串
      %d  格式化整数
      %u  格式化无符号整型
      %o  格式化无符号八进制数
      %x  格式化无符号十六进制数
      %X  格式化无符号十六进制数(大写)
      %f  格式化浮点数字,可指定小数点后的精度
      %e  用科学计数法格式化浮点数
      %E  作用同%e,用科学计数法格式化浮点数
      %g  %f和%e的简写
      %G  %f 和 %E 的简写
      %p  用十六进制数格式化变量的地址
2、举例
  1. >>> s ='So %s day!'
  2. >>>print(s %'beautiful')
  3. So beautiful day!
  4. >>> s %'beautiful!'
  5. 'So beautiful! day!'
  6. >>>'1 %c 1 %c %d'%('+','=',2)
  7. '1 + 1 = 2'
  8. >>>'x= %x'%0xA
  9. 'x= a'
  10. >>>'x= %X'%0xa
  11. 'x= A'
 
三 字符串和数字类型转换
1、int函数和str函数
int()函数将字符串转换为数字。
str()函数将数字转换为字符串。
2、举例
  1. >>>'10'+4
  2. Traceback(most recent call last):
  3. File"<pyshell#0>", line 1,in<module>
  4. '10'+4
  5. TypeError: must be str,not int
  6. >>> int('10')+4
  7. 14
  8. >>>'10'+ str(4)
  9. '104'
 
四 原始字符串
1、介绍
原始字符串是Python中一类比较特殊的字符串,以大写字母R或小写字母r开始,在原始字符串中,字符“\"不再表示字符的含义。
原始字符串是为正则表达式设计的,也可以用来方便地表示Windows系统下的路径,不过,如果以“\”结尾,那么会出错。
2、举例
  1. >>>import os
  2. >>> path = r'E:\python'
  3. >>> os.listdir(path)
  4. ['python_workspace','work']
  5. >>> os.listdir('E:\python')
  6. ['python_workspace','work']
  7. >>> patch = R'E:\python\'
  8. SyntaxError: EOL while scanning string literal

猜你喜欢

转载自cakin24.iteye.com/blog/2381299