字符串的连接
两个字符串可以通过’+‘连接
str1 = 'abc'
str2 = 'qwe'
print str1 +str2
>>>abcqwe
字符串的合并
用 join方法合并
url = ['www', 'baidu', 'com']
print '.'join(url)
>>>www.baidu.com
字符串相乘
"*"号跟相乘的次数
line = "-"*20
print line
>>>--------------------
字符串切片
str = 'hello world'
print str[0:4] //取第一个到第四个字符组成的字符串
>>>hell
print str[0:-2] //取第一个到倒数第二个字符组成的字符串
>>>hello wor
print str[::] //复制字符串
>>>hello world
字符串的分割
- 简单分割 用split
//1.简单分割
str = 'apple;banana;peach;egg;oil'
print str.split(';')
>>>['apple', 'banana', 'peach', 'egg', 'oil']
- 复杂分割 用re模块(使用正则表达式对字符串分割)
re.split(pattern, string, [maxsplit], [flags])
pattern 匹配的正则表达式
string 要匹配的字符串。
maxsplit 分隔次数,maxsplit=1 分隔一次,默认为 0,不限制次数。
flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
//2.复杂分割
import re
line = 'one1two2three3four4'
print re.split('\d+', line)
>>>['one', 'two', 'three', 'four', '']
判断字符串的头尾
使用endswith方法和startswith方法判断,返回类型为布尔型
filename = 'solver.h'
print filename.endswith('h')
>>>True
print filename.startswith('h')
>>>False
字符串中的查找定位
通过find方法查找子字符串,返回子字符串第一个字符所在位置的索引,若没有找到,则返回-1
str = '1234567890'
print str.find("456")
>>>3
使用正则表达式判断字符串匹配
import re
date = '2018/12/16'
if re.match(r'\d+/\d+/\d+',date):
print "match"
else:
print "not match"
>>>match
字符串的替换
a = 'I am 3 years old '
b = a.replace('3','1')
print b
>>>I am 1 years old
移除字符串首尾的指定字符
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
str.strip([chars]);
chars – 移除字符串头尾指定的字符序列。
返回移除字符串头尾指定的字符生成的新字符串。
str = 'hhhhhhhhhhh2222222243783hhhh'
print str.strip('h')
>>>2222222243783
str = ' 123 '
print str.strip()
>>>123