拆分字符串并删除空格Python [英] Splitting string and removing whitespace Python

查看:70
本文介绍了拆分字符串并删除空格Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用逗号分割一个字符串 ',' 并从每个分割的开头和结尾删除空格.

例如,如果我有字符串:

QVOD,百度播放器"

我想拆分和剥离:

['QVOD', '百度播放器']

有没有一种优雅的方式来做到这一点?可能使用列表推导式?

解决方案

Python 有一个名为 split 的壮观函数,它可以让您不必使用正则表达式或类似的东西.您只需调用 my_string.split(delimiter)

即可拆分字符串

在那之后,python 有一个 strip 函数,它将删除字符串开头和结尾的所有空格.

[item.strip() for my_string.split(',')]

这两种方法的基准如下:

<预><代码>>>>导入时间>>>timeit.timeit('map(str.strip, "QVOD,百度播放器".split(","))', number=100000)0.3525350093841553>>>timeit.timeit('map(stripper, "QVOD,百度播放器".split(","))','stripper=str.strip', number=100000)0.31575989723205566>>>timeit.timeit("[item.strip() for item in 'QVOD,Baidu Player'.split(',')]", number=100000)0.246596097946167

所以列表合成比地图快 33%.

可能还值得注意的是,就pythonic"而言,Guido 本人投票支持 LC.http://www.artima.com/weblogs/viewpost.jsp?thread=98196

I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split.

For example, if I have the string:

"QVOD, Baidu Player"

I would like to split and strip to:

['QVOD', 'Baidu Player']

Is there an elegant way of doing this? Possibly using a list comprehension?

解决方案

Python has a spectacular function called split that will keep you from having to use a regex or something similar. You can split your string by just calling my_string.split(delimiter)

After that python has a strip function which will remove all whitespace from the beginning and end of a string.

[item.strip() for item in my_string.split(',')]

Benchmarks for the two methods are below:

>>> import timeit
>>> timeit.timeit('map(str.strip, "QVOD, Baidu Player".split(","))', number=100000)
0.3525350093841553
>>> timeit.timeit('map(stripper, "QVOD, Baidu Player".split(","))','stripper=str.strip', number=100000)
0.31575989723205566
>>> timeit.timeit("[item.strip() for item in 'QVOD, Baidu Player'.split(',')]", number=100000)
0.246596097946167

So the list comp is about 33% faster than the map.

Probably also worth noting that as far as being "pythonic" goes, Guido himself votes for the LC. http://www.artima.com/weblogs/viewpost.jsp?thread=98196

这篇关于拆分字符串并删除空格Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆