python字符串处理

1.字符串的切片和相乘切片

(1)切片

str = 'Monday is busy day'
print(str[0:7])           #表示取第一个到第七个的字符串
print(str[-3:])           #表示取从倒数第三个字符串开始到结尾的字符串
print(str[::])            #复制字符串

(2)相乘

当外面编写python代码时要分隔符,此时用字符串的乘法就很容易实现

line = '*'*30
print(line)

>> ******************************

 

2.字符串的分割

(1)普通的分割,用split函数,但是spilt只能做非常简单的分割,而且不支持多个分割。

phone = '400-800-800-1234'
print(phone.split('-'))

>>['400', '800', '800', '1234']

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

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

>>>['hello world', 'python', 'I ', 'like', 'it']

3.字符串的连接和合并

(1)连接,两个字符可以很方便的通过“+”连接起来

str1='Hello'
str2='World'
new_str=str1+str2
print(new_str)

>>>HelloWorld

(2)合并,用join方法

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

>>>www.python.org

 

4.判断字符串是否以指定前缀、后缀结尾

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

filename='trace.h'

print(filename.endswith('h'))

>>True

print(filename.startswith('trace'))

>>True

 

5.字符串的查找和匹配

(1)一般查找

利用find方法可以很方便的在长的字符串里面查找子字符串,会返回字符串所在位置的索引,若找不到返回-1

str1 = "this is string example....wow!!!"
str2 = "exam"
print(str1.find(str2))      # 15
print(str1.find(str2, 10))  # 15
print(str1.find(str2, 40))  # -1

(2)复杂的匹配,就需要用到正则表达式。

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

>>>ok.match

 

6.统计字符串里某个字符出现的次数

str = "thing example....wow!!!"
print(str.count('i', 0, 5))  # 1
print(str.count('e'))  # 2

 

7.字符串的替换

(1)普通的替换,用replace方法就可以了

text='python is an easy to learn,powerful programming language.'
print(text.replace('learn','study'))

>>>python is an easy to study,powerful programming language.

(2)复杂的替换,需要用到re模块的sub函数

sub函数详解 https://blog.csdn.net/mrzhoug/article/details/51585615

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

>>>Boy 100,girl 100

 

8.去掉字符串中一些特定的字符

(1)去空格,对文本处理的时候比如从文件中读取一行,然后需要去除每一行的空格、table或者是换行符。

str = ' python str '
print(str)
# 去首尾空格
print(str.strip())
# 去左侧空格
print(str.lstrip())
# 去右侧空格
print(str.rstrip())

(2)复杂的文本清理,可以利用str.translate。

比如先构建一个转换表,table是一个翻译表,表示把“to”转成大写的“TO”,然后在old_str里面去掉‘12345’,然后剩下的字符串再经过table翻译。

instr = 'to'
outstr = 'TO'
old_str = 'Hello world , welcome to use Python. 123456'
remove = '12345'
table = str.maketrans(instr,outstr,remove)
new_str = old_str.translate(table)
print(new_str)

>>>HellO wOrld , welcOme TO use PyThOn. 6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值