字符串的特性
s = ‘hello’ # 索引:0 1 2 3 4 索引从0开始
print(s[0])
print(s[1])
拿出最后 一个字符
print(s[4])
print(s[-1])
s[start:stop:step] 从satrt开始到end -1结束
步长为step
print(s[0:3])
print(s[0:4:2])
显示所有的字符
print(s[:])
显示前3个字符
print(s[:3])
字符串的反转
print(s[::-1])
除了第一个字符之外的其他全部字符
print(s[1:])
重复
print(s * 10)
连接
print('hello ' + 'python')
成员操作符
print('he' in s)
print('aa' in s)
print('he' not in s)
for循环遍历
for i in s:
print(i)
字符串练习——输出正反一样的数
num = input('Num:')
print(num == num[::-1])
字符串常用方法
"""
>>> 'hello'.istitle() #判断是否是标题
False
>>> 'hello'.isupper() #判断是否全为大写
False
>>> 'Hello'.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'hello'.islower() #判断是否全为小写
True
>>> 'Hello'.islower()
False
>>> 'Hello'.lower() #全转化为小写
'hello'
>>> a = 'Hello'.lower()
>>> a
'hello'
>>> a = 'Hello'.upper() #全转化为大写
>>> a
'HELLO'
>>> a = 'Hello'.title() #转化为标题
>>> a
'Hello'
"""
注意:去除左右两边的空格,空格为广义的空格 包括:\t \n
>>> s = ' hello'
>>> s
'\thello'
>>> s = ' hello'
>>> s
' hello'
>>> s.lstrip() #去除左空格
'hello'
>>> s = ' hello '
>>> s
' hello '
>>> s.lstrip()
'hello '
>>> s.rstrip() #去除右空格
' hello'
>>> s.strip() #去除空格
'hello'
>>> s = ' hello'
>>> s
'\thello'
>>> s.strip()
'hello'
>>> s = ' hello\n'
>>> s
'\thello\n'
>>> s.strip()
'hello'
>>> s = 'helloh'
>>> s.strip('h') #去除h
'ello'
>>> s.lstrip('h') #去除左h
'elloh'
字符串常用内容)
#输出以.log结尾的文件名称
filename = 'hello.loggg'
if filename.endswith('.log'):
print(filename)
else:
print('error.file')
爬取以http开头的内容
url = 'http://172.25.254.250/index.html'
if url.startswith('http://'):
print('%s' %(url))
else:
print('不能爬取~~')
字符串的判断
“”"
[[:digit:]] [[:alpha:]]
“”"
只要有一个元素不满足,就返回False
print('weeeqwe32131'.isdigit())
print('42131321fsas'.isalpha())
print('weewqeq323213'.isalnum())
字符串练习–判断变量名是否合法
“”"
变量名定义是否合法:
1.变量名可以由字母 数字 下划线组成
2.变量名只能以字母或者下划线开头
s = '321csv_' s[0] s[1:]
s = 'asfasf%%'
'_'
exit
"""
while True: #定义死循环
s = input('请输入变量名称:')
if s == 'exit':
print('Bye~~')
break
if s[0].isalpha() or s[0] =='_':
for i in s[1:]:
if not(i.isalnum() or i=='_'):
print('%s变量名不合法!!!'%s)
break
else:
print('%s变量名合法'%s)
else:
print('%s变量名不合法!!!'%s)
字符串的对齐
print('学生管理系统'.center(30))
print('学生管理系统'.center(30,'@'))
print('学生管理系统'.center(30,'&'))
print('学生管理系统'.ljust(30,'#'))
print('学生管理系统'.rjust(30,'#'))
字符串的替换
s = 'hello world hello'
find 找到子字符串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))
print(s.rfind('hello'))
替换字符串中的hello为redhat
print(s.replace('hello','redhat'))
字符串的统计
print('hello'.count('l')) #查找l所在位置并输出最小位置
print('hello'.count('ll'))
print(len('wfqfqfqfq')) #输出长度
字符串的分离和连接
s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])
date = '2019-8-28'
date1 = date.split('-')
print(date1)
连接 通过指定的连接符号 连接每个字符
print(''.join(date1))
print('/'.join(date1))
print('~~'.join('hello'))