简体   繁体   English

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

[英]removing a character from beginning or end of a string in Python

I have a string that for example can have - any where including some white spaces. 我有一个字符串,例如可以包含的字符串-任何包含空格的地方。 I want using regex in Python to remove - only if it is before all other non-whitespace chacacters or after all non-white space characters. 我想在Python中使用正则表达式删除-仅在所有其他非空白字符之前或所有非空白字符之后才删除。 Also want to remove all whitespaces at the beginning or the end. 还希望删除开头或结尾的所有空格。 For example: 例如:

string = '  -  test '

it should return 它应该返回

string = 'test'

or: 要么:

string = '  -this - '

it should return 它应该返回

string = 'this'

or: 要么:

string = '  -this-is-nice - '

it should return 它应该返回

string = 'this-is-nice'

You don't need regex for this. 您不需要正则表达式。 str.strip strip removes all combinations of characters passed to it, so pass ' -' or '- ' to it. str.strip strip删除传递给它的所有字符组合,因此将' -''- '传递给它。

>>> s = '  -  test '
>>> s.strip('- ')
'test'
>>> s = '  -this - '
>>> s.strip('- ')
'this'
>>> s =  '  -this-is-nice - '
>>> s.strip('- ')
'this-is-nice'

To remove any type of white-space character and '-' use string.whitespace + '-' . 要删除任何类型的空格字符和'-'使用string.whitespace + '-'

>>> from string import whitespace
>>> s =  '\t\r\n  -this-is-nice - \n'
>>> s.strip(whitespace+'-')
'this-is-nice'
import re
out = re.sub(r'^\s*(-\s*)?|(\s*-)?\s*$', '', input)

This will remove at most one instance of - at the beginning of the string and at most one instance of - at the end of the string. 这将删除最多一个实例-在字符串的开头和在最多一个实例-在字符串的结尾。 For example, given input - - text - - , the output will be - text - . 例如,给定输入- - text - - ,输出将为- text -

Note that \\s matches Unicode whitespaces (in Python 3). 请注意, \\s与Unicode空格匹配(在Python 3中)。 You will need re.ASCII flag to revert it to matching only [ \\t\\n\\r\\f\\v] . 您将需要re.ASCII标志将其还原为仅匹配[ \\t\\n\\r\\f\\v]

Since you are not very clear about cases such as -text , -text- , -text - , the regex above will just output text for those 3 cases. 既然你不看好的情况下,如很清楚-text-text--text -上述正则表达式将只输出text的这3例。

For strings such as text , the regex will just strip the spaces. 对于诸如text字符串,正则表达式只会去除空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM