专业编程基础技术教程

网站首页 > 基础教程 正文

Python数据分析笔记#7.3.1 字符串对象方法

ccvgpt 2024-08-09 12:03:58 基础教程 10 ℃


「目录」

Python数据分析笔记#7.3.1 字符串对象方法

数据清洗和准备

Data Cleaning and Prepration

  • 7.1 => 处理缺失数据
  • 7.2 => 数据转换
  • 7.3 => 字符串操作

--------> 字符串对象方法


字符串对象方法

Python能够成为流行的数据处理语言的部分原因是其易于处理字符串和文本。大部分文本运算都直接做成了字符串对象的内置方法。

split方法可以通过指定分隔符对字符串进行切片

例如,以逗号分割的字符串可以用split拆分成数段:

In [1]: val = 'a,b, guido'

In [2]: val.split(',')
Out[2]: ['a', 'b', ' guido']

strip可以去除字符串头尾指定的字符,默认是空白符或换行符。

strip常常与split一起使用:

In [3]: pieces = [x.strip() for x in val.split(',')]

In [4]: pieces
Out[4]: ['a', 'b', 'guido']

利用加法可以将字符串连接起来

In [5]: first, second, third = pieces

In [6]: first + '::' + second + '::' + third
Out[6]: 'a::b::guido'

但这种方式并不实用,毕竟字符串多了就很麻烦。一种更快更符合Python风格的方式是是使用join方法,我们向join方法中传入一个列表或元组:

In [7]: '::'.join(pieces)
Out[7]: 'a::b::guido'

检测子串的最佳方法是利用Python的in关键字,还可以使用index和find。

index和find会查找指定值的首次出现的位置

In [8]: 'guido' in val
Out[8]: True

In [9]: val.index(',')
Out[9]: 1

find和index的区别是:若找不到字符串,index将会引发一个异常,find则会返回-1

In [10]: val.find(':')
Out[10]: -1

In [11]: val.index(':')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-2c016e7367ac> in <module>
----> 1 val.index(':')

ValueError: substring not found

count可以返回指定字串的出现次数

In [12]: val.count(',')
Out[12]: 2

replace用于将指定模式替换为另一个模式(replace will substitute occurrences of one pattern for another)

In [13]: val.replace(',', '')
Out[13]: 'ab guido'

再记录几个Python内置的字符串方法吧。

startswith和endswith:若字符串以某个前缀(后缀)开头,则返回True

In [14]: new_str = 'Shanghai'

In [15]: new_str.startswith('Sh')
Out[15]: True

In [16]: new_str.endswith('hai')
Out[16]: True

lower和uppe:分别将字母字符转换为小写或大写

In [17]: 'I love you'.lower()
Out[17]: 'i love you'

In [18]: 'I love you'.upper()
Out[18]: 'I LOVE YOU'

ljust和rjust:用空格(或其他字符)填充字符串的空白侧以返回符合最低宽度的字符串

In [21]: new_str2 = 'This is a test'

In [22]: new_str2.ljust(30, '!')
Out[22]: 'This is a test!!!!!!!!!!!!!!!!'

In [23]: new_str2.rjust(30, '!')
Out[23]: '!!!!!!!!!!!!!!!!This is a test'

这章终于还剩两节就结束了。


-END-

最近发表
标签列表