前言
本节针对字符串这个基本类型做个熟悉。
正文
字符串拼接
tang_str="hello python"
print(tang_str)
hello python
tang = "hello" + "python"
print(tang)
hellopython
字符串长度
len(tang_str)
12
字符串乘以固定值,会得到什么样的结果
tang_str * 3
'hello pythonhello pythonhello python'
字符串拆分
tang = '1 2 3 4 5'
tang.split()
['1', '2', '3', '4', '5']
tang = '1,2,3,4,5'
tang = tang.split(",")
print(tang)
['1', '2', '3', '4', '5']
字符串合并,按照固定分隔符
tang_str = ' '
tang_str.join(tang)
'1 2 3 4 5'
字符串替换
tang = 'hello python'
tang.replace("python", "world")
'hello world'
print(tang)
hello python
字符串大写输出
tang.upper()
'HELLO PYTHON'
字符串小写输出
tang.lower()
'hello python'
字符串去除左右空格
tang2 = " hello python "
tang2.strip()
'hello python'
字符串去除左空格
tang2.lstrip()
'hello python '
字符串去除右空格
tang2.rstrip()
' hello python'
字符串格式化输出
'{} {} {}'.format('chen', 'mo', 'hello')
'chen mo hello'
按照顺序 2 0 1代表传入参数的输出顺序
'{2} {0} {1}'.format('chen', 'mo', 'hello')
'hello chen mo'
'{chen} {mo}'.format(chen='mo', mo='chen')
'mo chen'
chen = "chen mo"
a = 123.0
b = 456
result = '%s%f%d' % (chen,a,b)
print(result)
chen mo123.000000456
索引
前面是从0开始
chen = "chen mo"
chen[0]
'c'
chen[5]
'm'
后面是从-1开始
chen[-1]
'o'
:表示左闭右开区间
chen[0:4]
'chen'
chen[5:]
'mo'
chen[:4]
'chen'
chen[4:-2]
' '
chen[-2:]
'mo'
chen[::2]
'ce o'
字符串中是否包含mo
'mo' in chen
True