定义字符串
string = ''
string1 = 'this is a string'
string2 = r'this is a raw string' # 原始字符串, 转义字符等均不转义原样输出
获取字符串长度
length = len(string1)
print(length) # 16
字符串判断
if 'is' in string1:
print('string1 含有 `is`')
if string1 == string2:
print('string1 与 string2 一样')
字符串拼接
n_str = 'this is ' + 'a string' # 使用 `+` 拼接
print(n_str) # this is a string
n_str = 'this is '
n_str += 'a string' # 使用 `+=` 拼接
print(n_str) # this is a string
n_str2 = 'num: ' + str(4) # 拼接数字
print(n_str2) # num: 4
设置字符串格式
format_str = '%s is a string. length: %d'%('this', 16) # 格式化, %f、%d、%s等格式, 和 C 语言基本上一致
print(format_str) # this is a string. length: 16
format_str = 'th{} {p1} a {p2}'.format('is', p2='string', p1='is')
# format_str = 'th{p1} {p1} a {p2}'.format(p2='string', p1='is')
# format_str = 'th{1} {1} a {0}'.format('string', 'is')
# format_str = '{0} is a {1}'.format('this', 'string')
# format_str = '{} is a {}'.format('this', 'string')
print(format_str) # this is a string
基本转换
t_str = 'The number is {num}'.format(num=88)
print(t_str) # The number is 88
t_str = 'The number is {num:f}'.format(num=88) # 浮点型
print(t_str) # The number is 88.000000
t_str = 'The number is {num:.2f}'.format(num=88) # 浮点型-保留2位小数
print(t_str) # The number is 88.00
t_str = 'The number is {num:010.2f}'.format(num=88) # 浮点型-保留2位小数,指定宽度, 如果不足则在前面补0
print(t_str) # The number is 0000088.00
t_str = 'The number is {num:b}'.format(num=88) # 二进制
print(t_str) # The number is 1011000
字符串简单切片(截取),高级切片此文暂时不介绍,以后会开新文章介绍
python 分正索引与负索引, 正索引和其他编程语言一样;负索引是从最后往前标识, 负索引是从-1
开始的
切片格式:str[截取开始索引:截取结束索引]
t_str = string1[:-3] # 从索引0开始截取到倒数第三个字符之前的位置
# t_str = string1[0:-3]
print(t_str) # This is a str
t_str = string1[:3] # 从索引0开始截取到索引3字符之前的位置
# t_str = string1[0:3]
print(t_str) # Thi
t_str = string1[5:7] # 从索引5开始截取到索引7之前的位置
print(t_str) # is
字符串分割与拼接
array = string1.split(' ') # 以空格分割字符串
print(array) # ['This', 'is', 'a', 'string']
t_str = '-'.join(array) # 以 `-` 将字符串数组拼接成字符串
print(t_str) # This-is-a-string
大小写转换
upp = string1.upper() # 转为大写
print(upp) # THIS IS A STRING
low = upp.lower() # 转为小写
print(low) # this is a string
去掉字符串前后的空白,不包含中间的空白
t_str = ' \n\n this is a string \n'.strip()
print(t_str) # this is a string
查找子字符串
index = string1.find('is a') # 如果查找到子字符串则返回子串的第一个字符的索引,否则返回 `-1`
print(index) # 5
替换字符串
t_str = string1.replace('string', 'raw string')
print(t_str) # This is a raw string
遍历字符串
for char in string1:
print(char)
'''
T
h
i
s
i
s
a
s
t
r
i
n
g
'''
还不快抢沙发