web-dev-qa-db-ja.com

Python:ワイルドカードワードを削除する

ポイントで区切られた単語の文字列があります。例:

_string1 = 'one.two.three.four.five.six.eight' 
string2 = 'one.two.hello.four.five.six.seven'
_

pythonメソッドでこの文字列を使用するには、ワイルドカードとして1つの単語を割り当てます(この場合、たとえば3番目の単語は異なるため)。どうすれば正規表現を考えていますが、私が考えているようなアプローチはpythonで可能です。

_string1.lstrip("one.two.[wildcard].four.")
_

または

_string2.lstrip("one.two.'/.*/'.four.")
_

(これをsplit('.')[-3:]で抽出できることはわかっていますが、一般的な方法を探しています。lstripは単なる例です)

12
aldorado

re.sub(pattern, '', original_string) を使用して、original_stringから一致する部分を削除します。

>>> import re
>>> string1 = 'one.two.three.four.five.six.eight'
>>> string2 = 'one.two.hello.four.five.six.seven'
>>> re.sub(r'^one\.two\.\w+\.four', '', string1)
'.five.six.eight'
>>> re.sub(r'^one\.two\.\w+\.four', '', string2)
'.five.six.seven'

ところで、あなたは誤解しています str.lstrip

>>> 'abcddcbaabcd'.lstrip('abcd')
''

str.replace の方が適切です(もちろん、re.subも):

>>> 'abcddcbaabcd'.replace('abcd', '')
'dcba'
>>> 'abcddcbaabcd'.replace('abcd', '', 1)
'dcbaabcd'
23
falsetru