【发布时间】: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