python中的字符串及字符串的处理
一.字符串的定义
多个字母、空格、数字都可以组成字符串,在定义字符串变量时,需要用双引号或单引号引起来,如果内容太多也可用三个双引
a = "league"
b = 'of'
c = "legend"
d = """
欢迎来到
新的世界
"""
print a
print b
print c
print d
可以看到打印出的变量的值是一串字符串
二.字符串的特性
1.索引:
s = 'hello'
print s[0]
print s[1]
在python中,索引的值(即下标)是从0开始的,即第一个字符的索引值为0,依次叠加
2.切片
切片的规则:sting [ start : end : step ] ,从start开始到end-1结束,步长为step,即每隔一个step取一次值
s = 'hello world'
print s[0:3]
print s[0:4:2]
s = 'how are you'
print s[:] ##显示所有字符 print s[:3] ##显示前3个字符 print s[::-1] ## 对字符串倒叙输出 print s[1:] ##除了第一个字符以外,显示其他全部字符 print s[:-1:] ##除了最后一个字符以外,显示其他全部字符
s = 'hello'
print s * 10 ##重复
print s + 'world' #字符的拼接
成员操作符
s = 'hello'
print 'q' in s
print 'he' in s
print 'aa' in s
三.字符串的处理
1.统计字符
print 'yasuoooo'.count('o')
2.搜索和替换
s = 'hello world'
print s.find('hello') ##搜索关键字符串,并返回其最小的索引值
print s.find('world')
print s.replace('hello','westos') ##替换指定字符串,后为替换内容
3.分离和连接
# 分离
ip = '172.25.254.250'
s1 = ip.split('.') ##以点号为分隔符号,提取字符串加入到列表中
print s1
date = '2018-8-27'
date1 = date.split('-')
print date1
# 连接
print ''.join(date1) ##以点号为连接符,将元组中的元素连接起来形成字符串
print '/'.join(date1)
print '/'.join('hello')
4.查询开头和结尾
url1 = 'http://www.baidu.com'
url2 = 'file:///mnt'
print url1.startswith('http://') ##找出字符串是否以XXX开头,关键字可自定义
print url2.startswith('f')
print url1.endswith('com') ##找出字符串是否以XXX结尾,关键字可自定义
print url2.endswith('mnt')
5.判断类型
print '123'.isdigit() ##判断字符串是否为数字
print '123abc'.isdigit()
print 'Hello'.istitle() ##判断某个字符串是否为标题(第一个首字母大写,其余字母小写)
print 'HeLlo'.istitle()
print 'hello'.isupper() ##判断字符串是否为大写字母
print 'hello'.islower() ##判断字符串是否为小写字母
print 'hello'.isalnum() ##判断字符串是否为字母和数字
print '123'.isalpha() ##判断字符串是否为字母
print ' '.isspace() ##判断字符串是否为空格