字符串(Strings)

字符串的定义:

在python3中,字符串是一个统一的序列。在python2中是一个字节的序列。字符串的很多特性和元组类似,字符串也是不可变的

# Python中的单引号和双引号结果是一样的
'
"
''' 
""" """

# 三个单引号或双引号通常用在字符串为多行的情况下
>>> s = 'jiangds'
>>> s
'jiangds'
>>> s = "东升"
>>> s
'东升'
>>> s = '''my name is jiangds
my years is 18
'''
>>> s
'my name is jiangds\nmy years is 18\

连接字符串

>>> lst = ['my', 'name', 'is', 'jiangds']
>>> lst
['my', 'name', 'is', 'jiangds']

>>> ' '.join(lst)    # 用空格连接
'my name is jiangds'

>>> ','.join(lst)    # 用逗号连接
'my,name,is,jiangds'

>>> 'my' +' name'
'my name'

>>> 'my' + 'age'
'myage'

>>> lst
['my', 'name', 'is', 'jiangds']

>>> s =''
    for x in lst:
        s += x 
        print(x)
my
name
is
jiangds

字符串分割

split()函数

从左边开始分割

>>> s = 'my name is jiangds'
>>> s.split()    # 默认是以空格为分隔符分割
['my', 'name', 'is', 'jiangds']

>>> s.split('is')    # 指定分隔符为'is'
['my name ', ' jiangds']

>>> s.split(' ', 1)    # 以空格为分隔符,最大分割次数为1
['my', 'name is jiangds']

>>> s.split(' ', 2)    # 以空格为分隔符,最大分割次数为2
['my', 'name', 'is jiangds']

>>> s.split(' ', -1)    # 负数不是最后一个,而是替换全部
['my', 'name', 'is', 'jiangds']

>>> line = 'url:http://jcrystal.cn'

>>> line.split(':', 1)    # 以冒号为分隔符,最大分割次数为1
['url', 'http://jcrystal.cn']

>>> key, value = line.split(':', 1)
>>> key
'url'
>>> value
'http://jcrystal.cn'

rsplit()函数

状态从句,与split()相反,是从右往左分割的

>>> line = 'url:http://jcrystal.cn:8080'
>>> line
'url:http://jcrystal.cn'

>>> line.rsplit(':', 1)
['url:http://jcrystal.cn', '8080']

splitlines

分割段

>>> text = '''i am ds
i am a boy 
i like girl'''
>>> text
'i am ds\ni am a boy\ni like girl'
>>> text.splitlines()
['i am ds', 'i am a boy', 'i like girl']
>>> text.splitlines(True)    # 默认是False,即去掉换行符\n,True的话即保留换行符
['i am ds\n', 'i am a boy\n', 'i like girl']
>>> text.splitlines(False)
['i am ds', 'i am a boy', 'i like girl']

partition 分割

在S中搜索分隔符seq,然后返回其前面的部分,分隔符本身及其后面的部分,如果找不到分隔符,则返回S和两个空字符串

>>> s
'my name is jiangds'
>>> s.partition(' ')
('my', ' ', 'name is jiangds')

>>> line.partition(':')
('url', ':', 'http://jcrystal.cn:8080')

>>> key, _, value = line.partition(':')
>>> key
'url'
>>> value 
'http://jcrystal.cn:8080'
>>> _
':'

字符串修改

字母大小写

大小写转化通常在做比较的时候,当我们需要忽略大小写比较时,通常统一转化为全部大写或者全部小写在做比较。字符串是不可变的,这里的修改是返回一个新的字符串

>>> s = 'my name is jiangds'

>>> s.capitalize()    # 首字母大写
'My name is jiangds'

>>> s.title()    # 所有单词首字母大写
'My Name Is Jiangds'

>>> s.lower()    # 所有字母单词小写
'my name is jiangds'

>>> s.upper()    # 所有字母单词大写
'MY NAME IS JIANGDS'

>>> s.upper().lower()    # 所有字母单词先全部大写在全部小写
'my name is jiangds'

>>> s2 = s.title()
>>> s2
'My Name Is Jiangds'

>>> s2.swapcase()    # 所有字母单词大小写反转
'mY nAME iS jIANGDS'

字符串填充、对齐、清除、修剪

>>> s
'my name is jiangds'

>>> s.center(50)    # 字符串在中间
'                my name is jiangds                '

>>> s.center(50, '#')    # 字符串在中间,两边用'#'填充
'################my name is jiangds################'

>>> s.ljust(50)    # 字符串在左边
'my name is jiangds                                '

>>> s.ljust(50, '*')    # 字符串在左边,右边用'*'填充
'my name is jiangds********************************'

>>> s.ljust(50) + '01'    # 类似于加目录编号
'my name is jiangds                                01'

>>> s.rjust(50)    # 字符串在右边
'                                my name is jiangds'

>>> s.rjust(50, '*')    # 字符串在右边,左边用'*'填充
'********************************my name is jiangds'

>>> s.zfill(50)    # 字符串在右边,左边用0填充
'00000000000000000000000000000000my name is jiangds'

>>> s1 = '    how are you  \n \t'
>>> s
'    how are you  \n \t'

>>> s1.strip()    # 去掉两边的空白符号(空格,制表符标签,换行符\ n)
'how are you'

>>> s1.lstrip()    # 去掉左边的空白符
'how are you  \n \t'

>>> s1.rstrip()    # 去掉右边的空白符
'    how are you'

>>> s2 = '###test###'
>>> s2.strip('#')
'test'

>>> s2.lstrip('#')
'test###'

>>> s2.rstrip('#')
'###test'

字符串判断

jds='''There was a Young Lady of Norway,
who casually sat in a doorway;
when the door squeezed her flat,
She exclaimed, "What of that?"
this courageous Young Lady of Norway.'''

>>> jds[:13]
'There was a Y'

>>> len(jds)    # 字符串长度
166

>>> jds.startswith('There')    # 以'There'开头
True

>>> jds.endswith('Norway')    # 以'Norway.'结尾
False

>>> jcds.endswith('Norway.')    # 所有字符串都是字母或数字吗? is*还有很多用法
True

>>> jcds.isalnum()    # 检测字符串是否由字母和数字组成
False

字符串(查找)

>>> s = 'abc123abc123'

>>> s.count('a')    # 字符串'a'出现了多少次
2

>>> s.index('a')    # 字符串'a'出现的第一次的位置
0

>>> s.rindex('a')    # 从右边开始查找,第一次出现字符串'a'的索引位置
6

>>> s.find('b')    # 查找第一次出现字符串'b'的索引位置
1

>>> s.find('abc')
0

>>> s.find('a', 0, 6)    # 查找从0到6,第一次出现字符串'a'的索引位置
0

>>> s.rfind('c')    # 从右边开始查找,第一次出现字符串'c'的索引位置
8

>>> s.find('s')    # 查找不存在的元素's',find会出现-1
-1

>>> s.index('s')    # 查找不存在的元素's',index会出现ValueError
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-5db391182dcb> in <module>()
----> 1 s.index('a')

ValueError: substring not found

字符串(替换)

>>> s
'abc123abc123'

>>> s.replace('abc', 'xyz')    # 默认替换所有
'xyz123xyz123'

>>> s.replace('abc', 'xyz', 1)    # 只替换第一个
'xyz123abc123'

>>> s.replace('xxx', '')
'abc123abc123'

>>> s.replace('abc', 'xyz', -1)    # 负数不是替换最后一个,还是替换所有
'xyz123xyz123'

>>> s
'abc123abc123'

>>> s[1:3]
'bc'

>>> s.replace('abc', 'xyz', 2)    # 不是替换第二个,还是替换所有
'xyz123xyz123'

>>> s.replace('abc', 'xyz', 2).replace('xyz', 'abc', 1)
'abc123xyz123'

字符编码

Python3使用str类型,底层实现使用Unicode编码
str --> encode --> bytes
bytes --> decode --> str

>>> s='东升'
>>> s
'东升'

>>> s.encode()
b'\xe4\xb8\x9c\xe5\x8d\x87'

>>> d=s.encode()
>>> d
b'\xe4\xb8\x9c\xe5\x8d\x87'

>>> d.decode()
'东升'
posted @ 2020-11-23 21:57  一墨无辰  阅读(462)  评论(0)    收藏  举报