2012-02-26 26 views
3

我是Python新手,在完成这一个脚本之后,我可能根本无法使用Python。我使用Scrapy提取一些数据,并且必须过滤掉一些字符串(我已经使用isdigit()来完成数字化)。谷歌搜索给我关于筛选特殊字符串的页面,但我想要的只是一个较大字符串的一小部分。筛选出一个较大字符串中的特定字符串?

这是字符串:

Nima Python: how are you? 

我想剩下的东西:

how are you? 

所以这部分删除:

Nima Python: 

在此先感谢球员。

回答

3

这工作:

>>> s = "Nima Python: how are you?" 
>>> s.replace("Nima Python: ", "") # replace with empty string to remove 
'how are you?' 
+0

的〔蟒手册](https://docs.python.org/2/library/string.html#string-functions)表示与string.replace已弃用。有没有不赞成的做法呢? – 2015-02-11 00:22:18

+0

@ChrisDodd'string.replace'已弃用。也就是说,模块'string'中的函数'replace'。 “str”对象的内置方法'replace'是一个不同的函数,不会被弃用。 – orlp 2015-02-11 19:37:29

2

字符切片:(这是最简单的方法,但不是很灵活)

>>> string = "Nima Python: how are you?" 
>>> string 
'Nima Python: how are you?' 
>>> string[13:] # Used 13 because we want the string from the 13th character 
'how are you?' 

替换字符串:

>>> string = "Nima Python: how are you?" 
>>> string.replace("Nima Python: ", "") 
'how are you?' 

字符串分割:(使用“:”将字符串拆分为两部分)

>>> string = "Nima Python: how are you?" 
>>> string.split(":")[1].strip() 
'how are you?' 
+0

以及你如何获得数字'13'? – neizod 2012-02-26 22:35:10

+0

刚刚计算出字符串中“how”的开始位置。我不同意,不是一个聪明的方法。 – varunl 2012-02-26 22:38:48

+0

@neizod:试试'Spring split'解决方案。它更通用。 – RanRag 2012-02-26 22:40:58

5

我假设会有其他字符串像这样...所以我猜str.split()可能是一个不错的选择。

>>> string = "Nima Python: how are you (ie: what's wrong)?" 
>>> string.split(': ') 
['Nima Python', 'how are you (ie', " what's wrong)?"] 
>>> string.split(': ', 1)[1] 
"how are you (ie: what's wrong)?" 
+0

string =“尼玛Python:不太好每个人似乎都忘记了'Nima Python'或':'可能会出现在右边的子字符串,但没关系,split和replace都带有一个参数,时间分割/替换“。 – DSM 2012-02-26 22:48:56

+0

这就是你使用'partition()'的原因。 – kindall 2012-02-27 02:04:28

+0

@DSM:你是对的。我应该使用_maxsplit_。 – rsaw 2012-02-27 03:08:35

3
>>> string = 'Nima Python: how are you?' 
>>> string.split(':')[1].strip() 
'how are you?' 
相关问题