在Python中从字符串的开头或结尾删除字符

TJ1*_*TJ1 1 python regex

我有一个字符串,例如可以有-任何包括一些空格的地方.我希望在Python中使用正则表达式-只在它出现在所有其他非空白字符之前或在所有非空白字符之后才能删除.还想删除开头或结尾的所有空格.例如:

string = '  -  test '
Run Code Online (Sandbox Code Playgroud)

它应该回来

string = 'test'
Run Code Online (Sandbox Code Playgroud)

要么:

string = '  -this - '
Run Code Online (Sandbox Code Playgroud)

它应该回来

string = 'this'
Run Code Online (Sandbox Code Playgroud)

要么:

string = '  -this-is-nice - '
Run Code Online (Sandbox Code Playgroud)

它应该回来

string = 'this-is-nice'
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 8

你不需要正则表达式.str.strip条去除传递给它的字符的所有组合,所以通过' -''- '给它.

>>> s = '  -  test '
>>> s.strip('- ')
'test'
>>> s = '  -this - '
>>> s.strip('- ')
'this'
>>> s =  '  -this-is-nice - '
>>> s.strip('- ')
'this-is-nice'
Run Code Online (Sandbox Code Playgroud)

删除任何类型的空白字符并'-'使用string.whitespace + '-'.

>>> from string import whitespace
>>> s =  '\t\r\n  -this-is-nice - \n'
>>> s.strip(whitespace+'-')
'this-is-nice'
Run Code Online (Sandbox Code Playgroud)


nha*_*tdh 2

import re\nout = re.sub(r'^\\s*(-\\s*)?|(\\s*-)?\\s*$', '', input)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这将最多删除-字符串开头的一个实例和-字符串末尾的最多一个实例。例如,给定输入-\xc2\xa0\xc2\xa0-\xc2\xa0text\xc2\xa0\xc2\xa0-\xc2\xa0-\xc2\xa0,输出将为-\xc2\xa0text\xc2\xa0\xc2\xa0-

\n\n

请注意,\\s匹配 Unicode 空格(在 Python 3 中)。您将需要re.ASCII标志将其恢复为仅匹配[ \\t\\n\\r\\f\\v]

\n\n

由于您不太清楚\xc2\xa0 -text, -text-,等情况-text -,因此上面的正则表达式将仅输出text这 3 种情况。

\n\n

对于诸如 之类的字符串\xc2\xa0\xc2\xa0text\xc2\xa0\xc2\xa0,正则表达式只会删除空格。

\n