从字符串的开头和结尾删除非字母字符

时间:2019-07-07 09:30:10

标签: python regex string

我对正则表达式非常陌生。我想从位于字符串开头和结尾的非字母字符中清除字符串。例如,如果我有以下字符串: .,How are you? I am good, thanks!.,

我想得到: How are you? I am good, thanks

3 个答案:

答案 0 :(得分:2)

使用

(\w|\s)+

表示任何character(\w)space(\s)至少具有one-time repeat(+)的人。

Demo

答案 1 :(得分:2)

您可以使用正则表达式:

^[^a-zA-Z]+|[^a-zA-Z]+$

[^a-zA-Z]的意思是“不是a-z或A-Z”。 ^$分别指字符串的开头和结尾。

用法:

>>> re.sub(r"^[^a-zA-Z]+|[^a-zA-Z]+$", "", ",. Hello, How are you?")
'Hello, How are you'

答案 2 :(得分:1)

您可以使用strip函数从字符串的开头和结尾删除字符

import string
nonalphabet= "".join([c for c in string.printable if c not in string.ascii_letters])
s = ".,how are you ?"
print (s.strip(nonalphabet))

将输出how are you