我有一根绳子。如何删除某个字符后的所有文本?(在这种情况下……) 之后的文字将…这就是为什么我想删除某一个字符之后的所有字符。
没有正则表达式(我假设这是你想要的):
def remafterellipsis(text):
where_ellipsis = text.find('...')
if where_ellipsis == -1:
return text
return text[:where_ellipsis + 3]
或者,使用正则表达式:
import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
在你的分离器上最多分裂一次,然后取出第一块:
sep = '...'
stripped = text.split(sep, 1)[0]
你没说如果分隔器不存在会发生什么。在这种情况下,这个和Alex的解决方案都会返回整个字符串。
假设你的分隔符是'…',但它可以是任何字符串。
text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')
>>> print head
some string
如果分隔符未找到,head将包含所有原始字符串。
分区函数是在Python 2.5中添加的。
S.partition(sep) ->(头,sep,尾) 搜索S中的分隔符sep,并返回它之前的部分, 分离器本身和后面的部分。如果分隔符不是 found返回S和两个空字符串。
另一种使用re的简单方法是
import re, clr
text = 'some string... this part will be removed.'
text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1)
// text = some string
如果你想删除一个字符串中最后出现的分隔符之后的所有内容,我发现这很好:
. join (string_to_split.split <分离器>(<分离器>)[1]):
例如,如果string_to_split是一个像root/location/child/too_far.exe这样的路径,并且你只想要文件夹路径,你可以通过"/".join(string_to_split.split("/")[:-1])分割,你将得到 根/位置/孩子
import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)
输出:“这是一个测试”
从文件中:
import re
sep = '...'
with open("requirements.txt") as file_in:
lines = []
for line in file_in:
res = line.split(sep, 1)[0]
print(res)
find方法将返回字符串中的字符位置。然后,如果你想从角色中删除所有东西,这样做:
mystring = "123⋯567"
mystring[ 0 : mystring.index("⋯")]
>> '123'
如果你想保留字符,在字符位置上加1。
这是在python 3.7工作到我 在我的情况下,我需要删除后点在我的字符串可变费用
费用= 45.05 Split_string = fees.split(".", 1)
[0] . Substring = split_string
打印(字符串)
还有一种方法是删除字符串中字符最后一次出现之后的所有字符(假设您想删除最后一个'/'之后的所有字符)。
path = 'I/only/want/the/containing/directory/not/the/file.txt'
while path[-1] != '/':
path = path[:-1]
推荐文章
- 什么是sys。maxint在Python 3?
- 如何在Python中连接文本文件?
- Python:从列表中获取前10个结果
- Psycopg2:用一个查询插入多行
- 通过urllib和python下载图片
- 如何在Python中拆分这一长行?
- Python中带有回溯的日志异常
- 如何在python中删除特定字符后的所有字符?
- 谷歌Colab:如何从我的谷歌驱动器读取数据?
- Keras,如何得到每一层的输出?
- 当需要一个1d数组时,传递一个列向量y
- 在TensorFlow中,Session.run()和tensoreval()之间的区别是什么?
- 折叠单元在jupyter笔记本
- 从url读取csv
- 如何打印一个groupby对象