Python中字符串处理操作

字符串的连接

两个字符串可以通过’+‘连接


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

字符串的分割

  1. 简单分割 用split
//1.简单分割

str = 'apple;banana;peach;egg;oil'
print str.split(';')

>>>['apple', 'banana', 'peach', 'egg', 'oil']

  1. 复杂分割 用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值