Python基础:数据类型-字符串(7)

1.字符串基本操作

  字符串是由字符组成的一串字符序列,字符串是有顺序的,从左到右,索引从0开始,依次递增。

  Python中字符串类型:str。

  Python中字符串的三种表示方式:

  (1)普通字符串:采用单引号(')或双引号(")括起来的字符串。

  (2)原始字符串(raw string):在普通字符串的前面加 r,字符串中的特殊字符不需要转义。

  (3)长字符串:字符串中包含换行、缩进等排版字符,使用三重单引号(''')或三重双引号(""")括起来的字符串。

1.1 普通字符串

  Python中字符串采用Unicode编码。

>>> s='Hello World!'
>>> s
'Hello World!'

  转义字符:

转义字符描述
\(在行尾时) 换行
\t 水平制表符
\n 换行
\r 回车
\" 双引号
\' 单引号
>>> s='Hello\tWorld!'
>>> print(s)
Hello   World!

1.2 原始字符串

  原始字符串:在普通字符串前面加 r。原始字符串可以直接按照字符串使用,没有转义符。

>>> s=r'Hello\tWorld!'
>>> print(s)
Hello\tWorld!

1.3 长字符串

  长字符串可以包含换行、缩进等排版字符。

>>> s='''Hello
...  World!'''
>>> print(s)
Hello
 World!

2.字符串格式化

  Python提供3种字符串格式化方法:

  (1)%运算符

  (2)内置函数format()

  (3)创建字符串对象配合format(),使用{}进行替换

2.1 %运算符 — 格式字符串

  语法:

%[flag][width][.precision]

  其中,%:标记转换说明符开始

     flag:转换标记

     width:最小宽度,转换后的值所保留的最小字符个数。如果是*,则宽度从值元组中读取。

     precision:精度,如果转换的实数,精度表示出现在小数点后的位数;如果转换的是字符串,则表示最大宽度。如果是*,则精度从值元组中读取。

  宽度和精度都是整数,通过点号(.)分隔。两个都是可选参数,如果给出精度,则必须包含点号。

  转换类型:

符号描述符号描述
%c 格式化字符及其ASCII码 %s 格式化字符串
%d 格式化整型 %u 格式化无符号整型
%o 格式化无符号八进制数 %x,%X 格式化无符号十六进制
%f 格式化浮点数字,可指定精度值 %e,%E 用科学计数法格式化浮点数
%g,%G %f和%e的简写,十进制整数或浮点数。 %% 输出数据时显式百分号
%r 使用repr()函数输出    

  转换标志(flag):

符号描述符号描述
'#' 十六、八进制进行转换时,可在前方补0。 '0' 数值前补0
'-' 靠左对齐,若与0同时使用,会优先于0。 '' 保留一个空格
> 靠右对齐 < 靠左对齐
+ 在转换值前加正负号    
>>> '%c'%97 # ASCII码输出字符
'a'
>>> '年同比变化:%.2f%%'%120.987 # 输出百分号
'年同比变化:120.99%'
>>> '%o'%10 # 转换八进制数
'12'
>>> '%#o'%10 # 转换补0八进制数
'0o12'
>>> '%x'%127 # 转换十六进制数
'7f'
>>> '%#x'%127 # 转换补0十六进制数
'0x7f'
>>> from math import pi
>>> '%010.5f'%pi # pi转换:带5位小数、长度为10、位数不足0填充的字符串
'0003.14159'
>>> s = '%-10.5f'%pi # 左对齐
>>> s
'3.14159   '
>>> len(s)
10
>>> s = '%-010.5f'%pi # -优先于0
>>> s
'3.14159   '
>>> '%10.5f'%pi # 空格填充
'   3.14159'
>>> '%-+10.5f'%pi # 左对齐显示正负符号
'+3.14159  '
>>> '%+-10.5f'%pi # 左对齐显示正负符号
'+3.14159  '
>>> '%-+10.5f'%-pi # 左对齐显示正负符号
'-3.14159  '
>>> '%3.5f'%pi #最小宽度 < 实际宽度,显示实际宽度
'3.14159'
>>> '%.5s'%('Hello World') # 字符串精度值:最大宽度
'Hello'
>>> s = '%10.5s'%('Hello World') # 字符串截取最大宽度后空格填充
>>> s
'     Hello'
>>> len(s)
10
>>> '%.*s'%(5,'Hello World') # 精度从元组中读取
'Hello'
>>> '%*.*s'%(10,5,'Hello World') # 宽度、精度从元组中读取
'     Hello'

2.2 内置函数format()

 

>>> '{:,}'.format(10000) # 千分位
'10,000'

 

3.字符串方法

3.1 find()方法

  find()方法:用于检测字符串中是否包含子字符串sub。如果指定start(开始)和end(结束),则在指定范围内检测。

        如果包含子字符串,返回开始的索引;否则返回-1。

  find()语法:

str.find(sub[, start[, end]])

  其中,sub:指定检测的子字符串,

     start:开始索引,默认为0;

     end:结束索引,默认为字符串的长度。

  返回结果为子字符串所在位置的最左端索引,如果没有找到,则返回-1。

  help查看find()方法定义:

>>> help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

  rfind()方法:与find()方法类似,区别是找到返回最右端位置的索引。

>>> help(str.rfind)
Help on method_descriptor:

rfind(...)
    S.rfind(sub[, start[, end]]) -> int
    
    Return the highest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.
>>> field = 'Hello World'
>>> field.find('o')
4
>>> field.rfind('o')
7
>>> field.find('o',5) # 指定开始索引    
7
>>> field.find('a') # 未找到则返回-1        
-1
>>> words = 'Where there is a will,there is a way.'
>>> len(words)
37
>>> words.find('is')
12
>>> words.rfind('is')
28

3.2 join()方法

  join()方法:用于将序列中的元素以指定字符连接成一个新的字符串。

  join()语法:

str.join(seq)

  其中,str:指定字符

     seq:待连接的元素序列

     返回结果:指定字符连接序列中元素后生成的新字符串

>>> dirs = ['','usr','bin','python3']
>>> mark = '/'
>>> mark.join(dirs)
'/usr/bin/python3'

4.字符串与数字相互转换

4.1 字符串转换数字

  int()或float():字符串转换数字,如果转换成功,则返回数字;否则引发异常。

>>> int('9')
9
>>> int('9.6')
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    int('9.6')
ValueError: invalid literal for int() with base 10: '9.6'
>>> float('9.6')
9.6

  默认情况下int()函数都将字符串参数作为十进制数字进行转换,可以指定基数(进制)。

>>> int('a')
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    int('a')
ValueError: invalid literal for int() with base 10: 'a'
>>> int('a',16)
10
>>> int('ab',16)
171
>>> int('h',16)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    int('h',16)
ValueError: invalid literal for int() with base 16: 'h'

4.2 数字转换字符串

  数字转换字符串有很多方法,另外Python中字符串提供str()函数。

>>> str(9.6)
'9.6'
>>> str(True)
'True'
>>> str([1,2,3])
'[1, 2, 3]'

  str()函数所有类型都可以转换,但缺点是不能格式化。如果格式化字符串可以使用format()函数。

>>> from math import pi
>>> '{:.2f}'.format(pi)
'3.14'
posted @ 2018-12-29 20:42  libingql  阅读(756)  评论(0编辑  收藏  举报