2016-08-04 8 views
2

Rのgsub関数に相当するシンプルな/ 1行のPythonはありますか?文字列の場合Rのgsubに相当する最も単純なpython

strings = c("Important text,  !Comment that could be removed", "Other String") 
gsub("(,[ ]*!.*)$", "", strings) 
# [1] "Important text" "Other String" 

答えて

5

import re 
string = "Important text,  !Comment that could be removed" 
re.sub("(,[ ]*!.*)$", "", string) 

あなたは文字列のリストであるためにあなたの質問を更新しているので、あなたはリストの内包を使用することができます。

import re 
strings = ["Important text,  !Comment that could be removed", "Other String"] 
[re.sub("(,[ ]*!.*)$", "", x) for x in strings] 
+0

「re.sub」にはcount引数があります。 Rでは、 'gsub'はパターンのすべてのインスタンスを削除するので、' gsub( "th"、 ""、 "this other") 'は" oer "に戻ります。パターンのすべてのインスタンスを削除するようにpythonに指示するcountの引数を知っていますか? – lmo

+3

[docs](https://docs.python.org/2/library/re.html)による@Imo - "オプションの引数の数は、置き換えられるパターンの出現の最大数です。 ( 'x *'、 ' - '、 'abc')は ' - 'を返すので、パターンの空のマッチは前のマッチに隣接していないときにのみ置き換えられます。 abc- ' – JasonAizkalns

関連する問題