如何用一个单词替换不同的短语 - python

时间:2017-03-26 21:25:16

标签: python python-2.7 replace

在学习python时,我正在使用replace()方法并尝试制作这个程序:

message = raw_input("Message to find the part of speech: ")
coordconj = "for" or "and" or "nor" or "but" or "or" or "yet" or "so"

print message.replace(coordconj, "coordinating conjunction")

如果我使用输入" name1 for name2"来运行它。输出是" name1协调连接名称2"但是" name1和name2"作为输入,它打印" name1和name2"

我也尝试过:

message = raw_input("Message to find the part of speech: ")


print message.replace("for" or "and" or "nor" or "but" or "or" or "yet" or "so", "coordinating conjunction")

但那也没有用。它只替换"因为"用"协调连接"。是否有任何方法可以将变量coorcon中的所有单词替换为"协调连接"没有使用一堆if语句?提前谢谢。

1 个答案:

答案 0 :(得分:-1)

'Number 87' --> 87
'data-2384729' --> 2384729
'Beep 8009 Bop' --> 8009

只是"for" or "and" or "nor" or "but" or "or" or "yet" or "so" ,因为非空字符串在Python中是Truthy而且"for"是懒惰评估的。

您可以在Python控制台中查看:

or

这是解决问题的可能方法:

>>> "for" or "and" or "nor" or "but" or "or" or "yet" or "so"
'for'

它已经改编自previous answer