2017-11-16 18 views
1

文字列を特定の文字に戻すにはどうすればよいですか?文字列内の特定の部分文字列の前後のすべてを取得する方法は?

def get_header(s): 
    '''(str) -> str 
    Return the start of the given string upto and including 
    </head>.''' 
    return (s.split('</head>')[0]) 

これは私がやったことですが、私は「」<「/頭の前にすべてを取得する方法を知らない」>「」と、それを含みます。例えば

s ="hello python world </head> , i'm a beginner " 
get_header(s) 

これはあなたのコードは動作するはずですが、"</head>"は含まれませんので、ちょうど最後にそれを追加

"hello python world "<"/head">" #without the quotient marks around the < 
+1

サンプル入力と期待される出力を投稿します。 –

答えて

1

を返します:

def get_header(s): 
    '''(str) -> str 
    Return the start of the given string upto and including 
    </head>.''' 
    return s.split('</head>')[0] + "</head>" 
0

これは、Pythonのreモジュールでは、「普通の式 "(または正規表現)を文字列に変換します。

は、ここであなたがやりたいためにそれを使用する方法は次のとおりです。

import re 

def get_header(s): 
    """(str) -> str 
    Return the start of the given string upto and including </head>. 
    """ 
    matches = re.search(r".*</head>", s) 
    return matches.group(0) if matches else None 

s = "hello python world </head> , i'm a beginner " 
print(get_header(s)) # -> hello python world </head> 
0

more_itertoolssplit_afterツールを実装して、サードパーティのライブラリです。経由してインストールします。

import more_itertools as mit 


s = "hello python world </head> , i'm a beginner " 

考える

> pip install more_itertools 

コード

pred = lambda x: x == "</head>" 
" ".join(next(mit.split_after(s.split(), pred))) 
# 'hello python world </head>' 

文字列は "言葉" へのスペースで分割されています。完全な文字列は、述語に合った単語の後に分割されます。最初の結果は一緒に結合されます。

関連する問題