[英]How to remove text from the beginning of a string based on condition?
假設我有以下文字:
'Reuters - Life is beautiful.'
'agency.com - China\'s currency remains pegged to the dollar and the US currency\'s sharp falls in recent months have therefore made - Chinese export prices highly competitive.'
'AP - The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.'
'CNN - Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.'
我只想刪除位於"-"
之前的文本開頭的所有文本,並且僅當"-"
后跟一個空格時。
我想要類似的東西:
if line.startswith(code_to_match_my_condition):
strip_matched_text_from_line
所以結果將是:
'Life is beautiful.'
'China\'s currency remains pegged to the dollar and the US currency\'s sharp falls in recent months have therefore made - Chinese export prices highly competitive.'
'The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.'
'Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.'
我實際上不知道如何編碼。 我將不勝感激。
非常感謝您提前
您可能想要使用正則表達式,例如
^[^-]+-\s+
並將其替換為空字符串,請參閱regex101.com 上的演示。
在Python
這可能是:
import re
strings = ['Reuters - Life is beautiful.',
'agency.com - China\'s currency remains pegged to the dollar and the US currency\'s sharp falls in recent months have therefore made - Chinese export prices highly competitive.',
'AP - The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.',
'CNN - Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.']
rx = re.compile(r'^[^-]+-\s+')
strings = list(map(lambda string: rx.sub("", string), strings))
print(strings)
和產量
['Life is beautiful.', "China's currency remains pegged to the dollar and the US currency's sharp falls in recent months have therefore made - Chinese export prices highly competitive.", 'The number of days that beaches closed or posted warnings because of pollution rose sharply in 2003 due to more rainfall, increased monitoring and tougher -standards, an environmental group said on Thursday.', 'Warming water temperatures - in the central equatorial Pacific last month may indicate the start of a new El Nino.']
用於搜索和刪除塊的簡單、可讀的代碼:
if " - " in line:
index = line.find(" - ")
line = line[index+3:]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.