Sol*_*ull 126 python replace python-2.6
我有一个字符串.如何删除某个字符后的所有文字?(在这种情况下...
)之后
的文本会...
改变,所以我这就是为什么我要删除某个字符后的所有字符.
Ned*_*der 223
最多在分隔符上拆分一次,然后取出第一块:
sep = '...'
rest = text.split(sep, 1)[0]
Run Code Online (Sandbox Code Playgroud)
你没有说如果没有分隔符会发生什么.在这种情况下,这个和Alex的解决方案都将返回整个字符串.
Aym*_*ieh 78
假设你的分隔符是'...',但它可以是任何字符串.
text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')
>>> print head
some string
Run Code Online (Sandbox Code Playgroud)
如果未找到分隔符,head
则将包含所有原始字符串.
分区函数在Python 2.5中添加.
分区(...)S.partition(sep) - >(head,sep,tail)
Run Code Online (Sandbox Code Playgroud)Searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns S and two empty strings.
the*_*cer 13
如果要在字符串中最后一次出现分隔符后删除所有内容,我发现这很有效:
<separator>.join(string_to_split.split(<separator>)[:-1])
例如,如果 string_to_split
是一个类似的路径,root/location/child/too_far.exe
并且您只想要文件夹路径,则可以拆分"/".join(string_to_split.split("/")[:-1])
并获得
root/location/child
没有RE(我认为是你想要的):
def remafterellipsis(text):
where_ellipsis = text.find('...')
if where_ellipsis == -1:
return text
return text[:where_ellipsis + 3]
Run Code Online (Sandbox Code Playgroud)
或者,与RE:
import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
Run Code Online (Sandbox Code Playgroud)
小智 6
import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)
Run Code Online (Sandbox Code Playgroud)
输出:“这是一个测试”
归档时间: |
|
查看次数: |
203170 次 |
最近记录: |