2009-02-14 69 views
2

确实有人知道如何删除特定字符后面的所有字符?在Python中删除字符

这样的:

http://google.com/translate_t 

http://google.com 
+0

这不是*真*删除 - Python无法更新字符串。这是提取一个子串到一个给定的位置。你可能想要重述你的问题。 – 2009-02-14 16:21:21

回答

2
str="http://google.com/translate_t" 
shortened=str[0:str.rfind("/")] 

应该这样做。 str [a:b]在python中返回一个子字符串。 rfind用于从字符串的末尾开始查找字符序列的索引。

+0

SilentGhost的分割版本更加清晰,IMO。 – 2009-02-14 17:52:42

+1

另外,如果字符串中没有“/”,则返回缩短一个字符的初始字符串。 – tzot 2009-02-14 20:28:16

2

如果您知道字符的位置,然后你可以用切片的语法来创建一个新的字符串:

In [2]: s1 = "abc123" 
In [3]: s2 = s1[:3] 
In [4]: print s2 
abc 

要发现你可以使用字符串的find()index()方法的位置。 split()partition()方法也可能有用。 这些方法记录在Python docs for sequences中。

删除一部分字符串是不可能的,因为字符串是不可变的。

如果你想处理URL,那么你应该使用urlparse library。它可以让你将URL分成不同的部分。如果你只是想删除一部分文件路径,那么你将不得不自己去做。

6

如果你问一个抽象的字符串,而不是网址,你可以一起去:

>>> astring ="http://google.com/translate_t" 
>>> astring.rpartition('/')[0] 
http://google.com 
5

对于网址,使用urlparse

>>> import urlparse 
>>> parts = urlparse.urlsplit('http://google.com/path/to/resource?query=spam#anchor') 
>>> parts 
('http', 'google.com', '/path/to/resource', 'query=spam', 'anchor') 
>>> urlparse.urlunsplit((parts[0], parts[1], '', '', '')) 
'http://google.com' 

对于任意的字符串,使用re

>>> import re 
>>> re.split(r'\b/\b', 'http://google.com/path/to/resource', 1) 
['http://google.com', 'path/to/resource']