字符串的创建
由单引号、双引号、及三层引号括起来的字符
str = 'hello,sheen'
str = "hello,sheen"
str = """hello,sheen""" #三层引号可输出内容的特定格式
转义字符
一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符
/t = 'tab',/n = '换行',/" = '双引号本身'
占位字符
| %d | 整数 |
| %f | 浮点数 |
| %s | 字符串 |
| %x | 十六进制整数 |
字符串的特性
索引
>>> h[0] #正向索引从0开始
'h'
>>> h[-1] #反向索引从-1开始
'o'
切片
s[start:end:step] # 从start开始到end-1结束, 步长为step;
- 如果start省略, 则从头开始切片;
- 如果end省略, 一直切片到字符串最后;
s[1:]
s[:-1]
s[::-1] # 对于字符串进行反转
s[:] # 对于字符串拷贝
成员操作符
in | not in
>>> 'o' in s
True
>>> 'a' in s
False
>>> 'a' not in s
True
连接
a = 'hello'
b='sheenstar'
print("%s %s" %(a,b))
hello sheenstar
a+b
'hellosheenstar'
a+' '+b
'hello sheenstar'
重复
print('*'*20+a+' '+b+"*"*20)
********************hello sheenstar********************
字符串常用方法
大小写
‘isalnum’, ‘isalpha’, ‘isdigit’, ‘islower’, ‘isspace’, ‘istitle’, ‘isupper’
‘lower’, ‘upper’, ‘title’
'Hello'.istitle() #判断是否是标题
True
'780abc'.isalnum() #判断是否是数字或字母
True
'780'.isdigit() #判断是否是数字
True
'abd'.isalpha() #判断是否是字母
True
'abd'.upper() #转换为大写
'ABD'
'ADE'.lower() #转换为小写
'ade'
'sheenSTAR'.swapcase()
'SHEENstar'
开头和结尾匹配
endswith
startswith
name = "yum.repo"
if name.endswith('repo'):
print(name)
else:
print("error")
yum.repo
去掉左右两边空格
strip
lstrip
rstrip
注意: 去除左右两边的空格, 空格为广义的空格, 包括: n, t, r
>h = ' hello '
>h.strip()
'hello'
>h
' hello '
>h.rstrip()
' hello'
>h
' hello '
>h.lstrip()
'hello '
搜索和替换
find:搜索
replace:替换
count:出现次数
>>> h = "hello sheen .hello python"
>>> h.find("sheen")
6
>>> h.rfind("sheen") #从右侧开始找,输出仍为正向索引值
6
>>> h.rfind("python")
19
>>> h.replace("sheen",'star')
'hello star .hello python'
>>> h
'hello sheen .hello python'
>>> h.count('hello')
2
>>> h.count('e')
4
分离与拼接
split:分离
join:拼接
>>> date = "2018/08/11"
>>> date.split('/')
['2018', '08', '11']
>>> type(date.split('/'))
<class 'list'>
>>>list=["1","3","5","7"]
>>>"+".join(list)
'1+3+5+7'