7招秘籍: 教你玩转Python字符串

日常使用python经常要对文本进行处理,无论是爬虫的数据解析,还是大数据的文本清洗,还是普通文件的处理,都是要用到字符串. Python对字符串的处理内置了很多高效的函数,非常方便功能很强大.下面是我总结的常用的7招,有了这几招就能轻松应对字符串处理.

1.字符串的连接和合并

连接和合并
相加 //两个字符串可以很方便的通过’+’连接起来

str1="Hello"
str2="World"
new_str=str1+str2 
print (new_str)
>>HelloWorld

合并//用join方法

url=['www','python','org']
print (''.join(url))
>>www.python.org

2.字符串的切片和相乘

1).相乘//比如写代码的时候要分隔符,用python很容易实现

line='*'*30
print (line)
>>******************************

2).切片

str='Monday is a busy day'
print (str[0:7])//表示取第一个到第7个字符
>>Monday 

print (str[-3:])
>>day 表示取倒数第三个字符开始到结尾

print (str[::])
>>Monday is a busy day

3.字符串的分割

普通的分割,用split
split只能做非常简单的分割,而且不支持多个分隔

phone='400-800-800-1234'
print(phone.split('-'))
>>['400', '800', '800', '1234']

复杂的分割
r表示不转义,分隔符可以是;或者,或者空格后面跟0个多个额外的空格,然后按照这个模式去分割

import re 
line='hello world; python, I ,like,'
print (re.split(r'[;,s]\s*',line))
>>['hello world', 'python', 'I ', 'like', '']

4.字符串的开头和结尾的处理

比方我们要查一个文件的名字是以什么开头或者什么结尾

filename='trace.h'
print(filename.endswith('h'))
>>True
print(filename.startswith('trace'))
>>True

5.字符串的查找和匹配

一般查找
我们可以很方便的在长的字符串里面查找子字符串,会返回子字符串所在位置的索引, 若找不到返回-1

title='Python can be easy to pick up and powerfullanguages'
print ('title.find('pick up'))
>>22

复杂的匹配

mydata='11/27/2016'
if re.match(r'\d+\d+\d+',mydata):
    print ('ok,match')
else:
    print ('ko,not match')

>>ok,match

6.字符串的替换
普通的替换//用replace就可以

title='Python can be easy to learn ,powerful languages'
print (title.replace('learn','study'))
>>Python can be easy to study ,powerful languages

复杂的替换//若要处理复杂的或者多个的替换,需要用到re模块的sub函数

students='Boy 103,gril 105'
print (re.sub(r'\d+',100,students))
>>'Boy 100,girl 100'

7.字符串中去掉一些字符
去除空格//对文本处理的时候比如从文件中读取一行,然后需要去除每一行的两侧的空格,table或者是换行符

line='  Congratulations, you guessed it.     '
print(line.strip())
>>Congratulations, you guessed it.
注意:字符串内部的空格不能去掉,若要去掉需要用re模块

复杂的文本清理,可以利用str.translate,
先构建一个转换表,table是一个翻译表,表示把’t”o’转成大写的’T’ ‘O’,

instr='to'
outstr='To'
table=str.maketrans(instr,outstr)
old_str='Hello world ,welcome to use Python'
new_str=old_str.translate(table)
print (new_str)
>>Hello world ,welcome To use PyThon
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值