上一篇
本次分享字符串。
正文
字符串的使用在python的开发过程中是最经常用到的数据类型,那么如何定义呢?
>>> strone='1'
>>> type(strone)
<class 'str'>
>>> strtwo="2"
>>> type(strtwo)
<class 'str'>
如何来访问字符串的值呢
>>> strtree="welcome beijing"
>>> strtree[1:]
'elcome beijing'
>>> strtree[1:-2]
'elcome beiji'
可以用索引查询, 索引是从0开始的,截取的时候,前包括后不包括,即:
[1:-2]即从第2个开始,到倒数第三个。
当然也可以取第几个
>>> strtree="welcome beijing"
>>> strtree[1]
'e'
这样就可以截取到了。
python字符串更新
>>> strtree="welcome beijing"
>>> strtree[1:-1]+'2'
'elcome beijin2'
先截取后拼接。
Python转义字符
>>> print("line \
... line2")
line line2
\ 加入后,可以换行编写字符串。
如何展示反斜杠
>>> print("line \\")
line \
如何展示单引号
>>> print("line \'")
line '
如何展示双引号
>>> print("line \"")
line "
展示换行
>>> print("line \n name")
line
name
纵向制表
>>> print("line \v name")
line
name
横向制表
>>> print("line \t name")
line name
Python字符串运算符
字符串拼接
>>> strone='hello '
>>> strtwo='leizi'
>>> strone+strtwo
'hello leizi'
重复输出多次
>>> strone*2
'hello hello '
获取
>>> strone='hello '
>>> strone[0]
'h'
截取
>>> strone[0:2]
'he'
是否存在
>>> strone='hello '
>>> 'h' in strone
True
是否不存在
>>> 'h' not in strone
False
Python 字符串格式化
>>> print ("我叫 %s !" % ('雷子'))
我叫 雷子 !
格式化字符串
print ("我叫 %s !" % ('雷子'))
我叫 雷子 !
格式化整数
>>> print (" %d !" % (100))
100 !
格式化浮点数
>>> print (" %f !" % (100.01))
100.010000 !
当然格式化还有其他的,这里列举的是常用的几个。
python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符
>>> name=""" name
... zhanshif
... nam"""
>>> name
' name\nzhanshif\nnam'
python3.6后新增: f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去,实例如下:
>>> name='hello'
>>> f'{name} leizi'
'hello leizi'
计算:
>>> f'{3*8}'
'24'
python字符串的内置方法
>>> dir(str)
['__add__', '__class__', '__contains__',
'__delattr__', '__dir__', '__doc__', '__eq__',
'__format__',
'__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable',
'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
使用:
首字母大写转化
>>> name='hello'
>>> name.capitalize()
'Hello'
查询字符串的个数
>>> name.count('l')
2
指定格式编码
>>> name.encode('utf-8')
b'hello'
检测结尾
>>> name='hello'
>>> name.endswith('o')
True
检测是否以什么开头
>>> name.startswith('o')
False
查找位置,不存在返回-1
>>> name='hello'
>>> name='hello'
4
>>> name='hello'
>>> name='b'
-1
查找位置,注意不存在会报错
>>> name='hello'
>>> name.index('0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> name.index('o')
4
如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
>>> name.isalnum()
True
如果只有数字
>>> name='hello'
>>> name.isdigit()
False
是否包含小写
>>> name.islower()
True
是否包含大写
>>> name.isupper()
False
是否只包含数字字符串
>>> name.isnumeric()
False
是否只包含空格
>>> name.isspace()
False
以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
>>> bei=''
>>> name=('2','3')
>>> bei.join(name)
'23'
长度
>>> len(name)
5
>>> name.__len__()
5
转化小写
>>> name.lower()
'hello'
截取
>>> name.lstrip('h')
'ello'
最大字母
>>> max(name)
'o'
最小字母
>>> min(name)
'e'
替换
>>> name='hello'
>>> name.replace('e','2')
'h2llo'
从右查找
>>> name.rfind('l')
3
从右边查找
>>> name.rindex('l')
3
>>> name.rindex('k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
返回指定长度,如果不满足就填补某个字符串
>>> name='hello'
>>> name.rjust(10,'8')
'88888hello'
删除置顶字符串
>>> name.rstrip('o')
'hell'
切割
>>> name.split('l')
['he', '', 'o']
判断什么开始
>>> name.startswith('h')
True
判断以什么结束
>>> name.endswith('h')
False
大写转小写,小写转大写
>>> name.swapcase()
'HELLO'
所有单词的字母转成大写
>>> name='hello word'
>>> name.title()
'Hello Word'
转化大写
>>> name.upper()
'HELLO WORD'
右对齐
>>> name='hello word'
>>> name.zfill(100)
'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000hello word'
上面列举了一些常用的方式。关于字符串自身的常用的方式就列举完毕了。