Python 数据类型 -- 字符串

– Start

什么是字符串?

字符串是不可变的,有序的字符序列。

如何构造字符串?

# 单引号
a = 'Hello World'

# 双引号
b = "Hello World"

# 三引号
c = '''Hello World'''

# 构造函数
d = str('Hello World')

如何操作字符串?

x = 'hello'
s = 'hello world'


#---------------- 根据索引访问字符
s[0]  # 正向索引
s[-1] # 反向索引
s[0:5] # 根据起始索引获取子串
s[0:5:2] # 根据起始索引获取子串,指定步长
s[:] # 复制字符串
s[:5] # 同 s[0:5]
s[2:] # 2 到结尾
s[::-1] # 反转字符串


#----------------
e = x + s # 字符串连接
e = s * 10 # 字符串重复

s.lstrip() # 去掉头部空格
s.rstrip() # 去掉尾部空格
s.strip() # 去掉头部和尾部空格


#---------------- 大小写转换
s.lower() # 返回小写字母
s.upper() # 返回大写字母
s.swapcase() # 大小写互换
s.casefold() # 返回小写字母

s.capitalize() # 返回首字母大写
s.title() # 每个单词首字母大写


#---------------- 子串操作
x in s
x not in s
s.startswith(x) # 字符串是否以 x 开始
s.endswith(x) # 字符串是否以 x 结尾

s.count(x) # 返回子串的数量

s.index(x) # 返回第一个子串的位置
s.rindex(x) # 返回最后一个子串的位置

s.find(x) # 返回第一个子串的位置
s.rfind(x) # 返回最后一个子串的位置

s.replace('0', 'o') # 把 0 替换为 o
s.expandtabs() # 将 tab 替换为空格


#---------------- 格式化
'hi {}'.format(s) # 格式化字符串
'my name is {name}'.format_map({'name':'shangbo'}) # 格式化字符串

s.center(20) # 返回 20 长度的字符串,s 居中对齐
s.ljust(20) # 返回 20 长度的字符串,s 左对齐
s.rjust(20) # 返回 20 长度的字符串,s 右对齐
'123'.zfill(20) # 返回 20 长度, 左边以 0 填充


#---------------- 合并分隔字符串
'1,2,3'.split(',')
'1,2,3'.rsplit(',')
'a\nb\n'.splitlines()

','.join(['x','x','x']) # 连接列表等可迭代数据结构

'a|b|c'.partition('|')
'a|b|c'.rpartition('|')


#---------------- 
len(s) # 返回字符串长度
min(s) # 返回最小值
max(s) # 返回最大值


#---------------- 
s.isalnum()
s.isalpha()
#s.isascii()
s.isdecimal()
s.isdigit()
s.isidentifier()
s.islower()
s.isnumeric()
s.isprintable()
s.isspace()
s.istitle()
s.isupper()


#---------------- 
s.encode(encoding="utf-8", errors="strict") # 将字符串转为 bytes
'ab'.translate(str.maketrans('a','b'))

– 更多参见:Python 精萃
– 声 明:转载请注明出处
– Last Updated on 2018-08-20
– Written by ShangBo on 2018-08-18
– End

猜你喜欢

转载自blog.csdn.net/shangboerds/article/details/81812718