[英]How to remove all characters after a specific character in python?
我有一個字符串。 如何刪除某個字符后的所有文本? (在這種情況下...
)
之后的文本將...
改變所以我這就是為什么我想在某個字符之后刪除所有字符。
最多在分隔符上拆分一次,然后取第一塊:
sep = '...'
stripped = text.split(sep, 1)[0]
你沒有說如果分隔符不存在會發生什么。 在這種情況下,this 和 Alex 的解決方案都將返回整個字符串。
假設您的分隔符是“...”,但它可以是任何字符串。
text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')
>>> print head
some string
如果沒有找到分隔符, head
將包含所有原始字符串。
分區函數是在 Python 2.5 中添加的。
partition(...) S.partition(sep) -> (head, sep, tail)
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.
如果您想在字符串中最后一次出現分隔符后刪除所有內容,我發現這很有效:
<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]
或者,使用 RE:
import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)
輸出:“這是一個測試”
方法 find 將返回字符串中的字符位置。 然后,如果您想從角色中刪除所有內容,請執行以下操作:
mystring = "123⋯567"
mystring[ 0 : mystring.index("⋯")]
>> '123'
如果要保留字符,請在字符位置加 1。
從文件:
import re
sep = '...'
with open("requirements.txt") as file_in:
lines = []
for line in file_in:
res = line.split(sep, 1)[0]
print(res)
使用 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
這是在 python 3.7 中對我工作在我的情況下,我需要在我的字符串變量費用中刪除點之后
費用 = 45.05
split_string = fee.split(".", 1)
子字符串 = split_string[0]
打印(子字符串)
另一種在字符串中最后一次出現字符后刪除所有字符的方法(假設您要刪除最后一個“/”后的所有字符)。
path = 'I/only/want/the/containing/directory/not/the/file.txt'
while path[-1] != '/':
path = path[:-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.