[Python]Python是否具有类似列表理解的字符串理解功能?

2024-06-01 05:08:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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

谢谢大家!


Tags: andtheto字符串in列表forstring
2条回答

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

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

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

from string import punctuation

punctuation返回字符串!“#$%&;'()*+,-./:;<;=>;?@[]^ `{124;}~

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'

相关问题 更多 >