【问题标题】:[Python]_ Does python has string comprehension like list comprehension?[Python]_ python 是否有像列表理解一样的字符串理解?
【发布时间】:2021-07-11 05:39:28
【问题描述】:

我正在学习 Python,我对字符串格式感到好奇。

我了解到有一个列表推导可以在 Python 中操作或创建列表。

例如,

li1 = [i for i in rage(10)]
# this will create a list name with li1
# and li1 contains following:
print(li1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

所以,我的问题是,如果我有下面的代码,有什么解决方案可以解决这个问题吗?喜欢使用列表推导?

# The task I need to do is remove all the pucntuations from the string and replace it to empty string.

text = input() # for example: "A! Lion? is crying..,!" is given as input
punctuations = [",", ".", "!", "?"]
punc_removed_str = text.replace(p, "") for p in punctuations
# above line is what I want to do.. 

print(remove_punctuation) 
# Then result will be like below:
    # Output: A Lion is crying

【问题讨论】:

  • 是的,也不是。字符串是序列,因此您可以在列表推导中使用它们,但结果始终是列表(或生成器,用于生成器表达式)。您必须使用.join() 或其他方法将其转换为字符串。

标签: python string list-comprehension


【解决方案1】:

Python 在标准库中已经有了一套完整的标点符号。

from string import punctuation

punctuation 返回字符串!"#$%&'()*+,-./:;?@[]^_`{|}~.

Docs

因此,您可以根据给定的输入创建一个列表,检查输入中的每个字符是否在 punctuation 字符串中。

>>> [char for char in text if char not in punctuation]
['A', ' ', 'L', 'i', 'o', 'n', ' ', 'i', 's', ' ', 'c', 'r', 'y', 'i', 'n', 'g']

您可以在内置的str.join 方法中传递结果列表。

>>> "".join([char for char in text if char not in punctuation])
'A Lion is crying'

【讨论】:

    【解决方案2】:

    没有字符串解析,但是您可以在 join() 内部使用生成器表达式,它用于列表解析中

    text = ''.join(x for x in text if x not in punctuations)
    print(text) # A Lion is crying
    

    【讨论】:

    • 小修正:括号内的内容是生成器表达式,而不是列表推导式。
    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 2018-09-17
    相关资源
    最近更新 更多