字符串操作
字符串对象处理方法
一个逗号分隔符的字符串可以使用split分成许多块:
val = 'a,b, guide'
print(val.split(','))
# ['a', 'b', ' guide']
split尝尝和strip一起使用,用于清除空格和换行:
val = 'a,b, guide'
pieces = [i.strip() for i in val.split(',')]
# ['a', 'b', 'guide']
`
我们也可以尝试将字符串通过某些字符连在一起:
```python
val = 'a,b, guide'
pieces = [i.strip() for i in val.split(',')]
frist,second,third = pieces
print(frist + '::' + second + "::" + third)
# a::b::guide
当然我们也可以使用一个更简单的方法:
val = 'a,b, guide'
pieces = [i.strip() for i in val.split(',')]
print("::".join(pieces))
# a::b::guide
使用in关键字或者index或者find方法可以判断一个字符是否存在与一个字符串中:
val = 'a,b, guide'
print("guide" in val)
# True
print(val.index(','))
# 1
print(val.find(':'))
# -1
find与index的区别是index在没有找到时会抛出异常而find则会返回-1
count方法可以返回某个特别字符串在字符串中穿线的次数:
val = 'a,b, guide'
print(val.count(','))
# 2
replace则可以将字符串的某一部分字符串替换为另外一字符串或者将其删除:
val = 'a,b, guide'
print(val.replace(',',"::"))
# a::b:: guide
print(val.replace(',',""))
# ab guide
下表为python内建的字符串方法
方法 | 描述 |
---|---|
count | 返回字符串在字符串中出现的次数 |
endwith | 如果字符串以传入的字符串为后缀则返回True |
startwith | 与endwith对应 |
join | 使用字符串作为间隔符,用于粘合字符串序列 |
index | 如果在字符串中找到指定的字符,则返回第一个字符的位置,如果没找到则抛出异常 |
find | 与index类似,但是如果没找到则返回-1 |
rfind | 如果在字符串中找到指定的字符,则返回最后一个字符的位置,没找到则返回-1 |
replace | 使用一个字符串代替另外一个字符串 |
strip,rstrip,lstrip | 修剪空白,包括换行符 |
split | 传入分隔符,将字符串拆分为字符串列表 |
lower | 将大写字母转换为小写字母 |
upper | 与lower相反 |
casefold | 将字符转换为小写,并将任何特定于区域的变量字符组合转换为常见的可比较形式 |
ljust,rjust | 左对齐或者右对齐;用空格(或者其他一些字符)填充字符串的相反侧以返回具有最小宽度的字符串 |
pandas中的向量化字符串
考虑下面这个Sereis对象:
import pandas as pd
import numpy as py
data = {'Dave':'dave@google.com',"Steve":"steve@gmail.com",
"Rob":"rob@gmail.com"," Wes":np.nan}
data = pd.Series(data)
# Dave dave@google.com
# Steve steve@gmail.com
# Rob rob@gmail.com
# Wes NaN
# dtype: object
可以使用str.contains来检查每一个邮箱地址是否含有‘gmail’:
res = data.str.contains('gmail')
print(res)
# Dave False
# Steve True
# Rob True
# Wes NaN
# dtype: bool
另外正则表达式也可以与这些函数进行结合:
print(data.str.findall(r'(\w+?)@([a-z0-9]+)\.([a-z0-9]+)',flags = re.IGNORECASE))
# Dave [(dave, google, com)]
# Steve [(steve, gmail, com)]
# Rob [(rob, gmail, com)]
# Wes []
有多种方法进行向量化的元素检测:
print(data.str.match(r'(\w+?)@([a-z0-9]+)\.([a-z0-9]+)'))
# Dave True
# Steve True
# Rob True
# Wes False
# dtype: bool
可以使用以下方式进行向量化切片:
print(data.str[:5])
# Dave dave@
# Steve steve
# Rob rob@g
# Wes NaN
# dtype: object
部分向量化字符串方法列表
方法 | 描述 |
---|---|
count | 模式出现的字数,参数为需要统计的字符串 |
extract | 使用正则表达式从字符串Series中分组抽取一个或者多个字符串;返回的结果是每个分组形成的一列DataFrame |
startwith | 等价于对每个元素使用x.startwith |
findall | 找出字符串中的所有模式/正则表达式匹配项,以列表返回 |
join | 根据传递的分隔符,将Series中的字符串联合 |
len | 计算字符串的长度 |
lower,upper | 转换大小写 |
match | 使用re.match将正则表达式应用到每个元素上,将匹配分组以列表形式返回 |
pad | 将空白加到字符串左边右边或者两边 |
center | 等价于pad(side = ‘both’) |
repeat | 重复值repeat(3)等价于将每个字符串*3 |
slice | 对Series中的字符串切片 |
split | 以分隔符或者正则表达式对字符串进行拆分 |
strip | 消除字符串两侧的空白和换行 |
rstrip,lstrip | 消除字符串左侧/右侧的空白和换行 |