【发布时间】:2017-08-19 11:18:10
【问题描述】:
在学习 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 协调连词 name2” 但是以“name1 and name2”作为输入,它会打印“name1 and 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")
但这也没有用。它只是用“并列连词”代替“for”。有没有办法在不使用一堆 if 语句的情况下将变量 coorcon 中的所有单词替换为“并列连词”?提前致谢。
【问题讨论】:
-
简而言之:
re.sub可能是最简单的方法,我建议您尝试打印coordconj的值,因为or不会做任何接近您认为的事情是的。 -
刷新页面。链接位于标题和正文之间。
-
我可以帮助你一点,让你知道你的表达
"for" or "and" or "nor" ...是有效的,但不是你想要的。相反,您正在执行逻辑操作,并且由于short-cicruit logic,将返回第一个字符串。也就是说,您的逻辑表达式的计算结果仅为“for”。
标签: python python-2.7 replace