Python自动化运维开发----基础(八)字符串

1.字符串(字符串也是列表的一种)

定义:单引号,双引号,三个单引号或者三个双引号引起来的 

字符串的访问方式:根据索引编号访问字符串:

字符串也是列表的一种

定义:单引号,双引号,三个单引号或者三个双引号引起来的 

2.字符串的访问方式

(1)根据索引编号访问

>>> name = "i am is KK"
>>> name[0]
'i'
>>> name[1]
' '
>>> name[2]
'a'

(2)遍历访问

>>> for i in name:
...     print(i)
... 
i
 
a
m
 
i
s
 
K
K

3.字符串函数

(1)len函数    统计字符串函数的长度

>>> len(name)
10

(2)max函数   字符串中最大的元素

>>> max(name)
's'

(3)min函数  字符串中最小的元素

>>> min(name)
' '

(4)cout函数  查询子字符串的数量

>>> name
'i am is KK'
>>> name.count('i')
2
>>> name.count(' ')
3

(5)index函数   获取元素的索引

>>> name
'i am is KK'
>>> name.index('i')
0
>>> name.index('a')
2

(6)find函数   查找元素的位置,不存在返回-1

>>> name.find('s')
6
>>> name.find('z')
-1

(7)查找字符串中的第二个空格

>>> name
'i am is KK'
>>> name.index(' ',name.index(' ')+1)
4

(8)startswith函数  以什么开头

>>> name.startswith('i')
True
>>> name.startswith('a')
False

(9)endswith函数  以什么结尾

>>> name.endswith('K')
True
>>> name.endswith('a')
False

(10)isalnum函数   字母或者数字

>>> 'a'.isalnum()
True
>>> '@'.isalnum()
False
>>> '1'.isalnum()
True

(11)isalpha函数 判断是不是字母

>>> 'i'.isalpha()
True
>>> '1'.isalpha()
False

(12)isdecimal函数 判断是不是数字

>>> '1'.isdecimal()
True
>>> 'a'.isdecimal()
False

(13)islower函数  判断是不是小写

>>> 'a'.islower()
True
>>> 'A'.islower()
False

(14)isupper函数   判断是不是大写

>>> 'a'.isupper()
False
>>> 'A'.isupper()
True

(15)join 函数  用子字符串把list连接起来

>>> a = ['a','b']
>>> ':'.join(a)
'a:b'

(16)split函数

>>> 'a:b:c'.split(':')
['a', 'b', 'c']

(17)upper函数 转换成大写

>>> 'a'.upper()
'A'

(18)lower函数  转换成小写

>>> 'A'.lower()
'a'

(19)replace函数  替换 

>>> 'abc abc'.replace('abc','x')
'x x'

(20)strip函数 取出字符串前后的空字符

>>> 'a n\f\n'.strip()
'a n'

去除指定的字符

>>> 'a b c'.strip('a')
' b c'
>>> 'a b c'.strip('a c')
'b'

(21)format函数

tpl模板

>>> tpl = 'my name is {0},and i\'m {1} years old!'
>>> name = 'likuan'
>>> age = 24
>>> tpl.format(name,age)
"my name is likuan,and i'm 24 years old!"

使用format函数传递参数

>>> '{name}-{age}'.format(name='likuan',age=24)
'likuan-24'

4.判断字符是否在字符串中

>>> 'a' in a
True
>>> 'a' not in a
False

字符串的特性 (字符串也是不可变的,不能修改和删除)

>>> a = "ab"
>>> a[0] = 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment


猜你喜欢

转载自blog.51cto.com/12217124/2343144