【问题标题】:How to get all the special characters as a list in Python? [closed]如何在 Python 中将所有特殊字符作为列表获取? [关闭]
【发布时间】:2020-06-14 15:10:35
【问题描述】:

如何将字符串中的所有非字母数字字符作为列表获取?

示例输入:

 spec!al Ch0racters are CO0l@!#

期望的输出:

 ['!', ' ', '@', '#']

【问题讨论】:

标签: python regex string list


【解决方案1】:

是否可以在 Python 中将特定字符串中的所有特殊字符作为列表获取?

如果我理解你,那可能会对你有所帮助:

string = "Special $#! characters   spaces 888323"
special_chars = list(set([e for e in string if not e.isalnum()]))
print(special_chars)

>>> ['#', ' ', '$', '!']

你可以使用str.isalnum:

S.isalnum() -> bool

Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.

如果您坚持使用正则表达式,其他解决方案也可以。但是请注意,如果它可以在不使用正则表达式的情况下完成,那是最好的方法。

正则表达式的方式是:

import re
print(list(set(re.sub('[A-Za-z0-9]+', '', string))))

【讨论】:

    【解决方案2】:

    是否可以在 Python 中以列表形式获取所有可用的特殊字符?

    您可以使用string.punctuation

    import string
    
    print(list(string.punctuation))
    #[!, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, ~]
    

    【讨论】:

      猜你喜欢
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 2013-05-16
      • 2021-04-26
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多