簡體   English   中英

從第一次出現的符號中刪除字符串尾部

[英]Remove string tail from first occurrence of a symbol

我需要從字符串中刪除注釋(如果存在)。 注釋以#開頭。

行可能有多個# 例如,“分隔符”行: ################################

有沒有比這更好的(單線)方法:

    ipound = line.find('#')
    if ipound >= 0:
        line = line[: ipound].rstrip()

rstrip是可選的,可以在注釋前刪除空格)

PS: if這樣就無法避免:

>>> line = "test"
>>> line = line[:line.find('#')]
>>> line
'tes'

這應該是刪除注釋並返回該行。

def remove_comment(line):
    return line.split('#')[0].rstrip()

line.index("#")返回第一次出現的“ #
然后,您可以使用字符串切片來獲取它之前的內容: line = line[:line.index("#")]
如果沒有 " # " 的實例,這將導致錯誤,所以改為line = line[:line.index("#")] if "#" in line else line

如果你想刪除字符串的結尾,我建議你使用re library 你可以用一行代碼做很多復雜的事情。

如果有#則刪除#之后的內容相當於保留#之前的所有內容,如果沒有#則保留所有內容。

import re 

string='hi#there'
new_string=re.findall('.*#?',string)[0]

>>>new_string='hi'

string2='hithere'
new_string_2=re.findall('.*#?',string2)[0]

>>>new_string='hithere'

你沒有指定你的字符串中是否有很多# 如果是,它只會考慮最后一個#

string3='hi#there#how are you ?'
new_string_3=re.findall('.*#',strign3)[0]

>>>new_string_3='hi#there#

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM