我的Data Structures类中有一个赋值,我正在使用Python来尝试解决它。我真的被Python困住了,所以请耐心等待。
Read a sentence from the console.
Break the sentence into words using the space character as a delimiter.
Iterate over each word, if the word is a numeric
value then print its value doubled, otherwise print out the word,
with each output on its own line.
Sample Run:
Sentence: Hello world, there are 3.5 items.
Output:
Hello
world,
there
are
7
items.
import string
import re
def main():
string=input("Input a sentence: ")
wordList = re.sub("[^\w]", " ", string).split()
print("\n".join(wordList))
main()
这给了我这个输出:
>>>
Input a sentence: I like to eat 7 potatoes at a time
I
like
to
eat
7
potatoes
at
a
time
>>>
所以我的问题是弄清楚如何提取数值然后加倍。我不知道哪里开始。
任何反馈都会受到赞赏。谢谢!
答案 0 :(得分:4)
尝试将值转换为float。如果它失败了,假设它不是浮点数。 :)
def main():
for word in input("Input a sentence: ").split():
try:
print(2 * float(word))
except ValueError:
print(word)
以上仍然会打印7.0
而不是7,这不是严格的规格。您可以使用简单的条件和is_integer
方法来解决此问题。
答案 1 :(得分:2)
在这里:
print("\n".join(wordList))
您可以使用列表推导来确定该单词是否为数字。也许是这样的:
print('\n'.join(str(int(i)*2) if i.isdigit() else i for i in wordList)
通过使用str.isdigit
查找看似整数的字符串,将其转换为整数,以便我们将其乘以2,然后将其转换回字符串。
对于花车,try/except
结构在这里很有用:
try:
print('\n'.join(str(int(i)*2) if i.isdigit() else i for i in wordList)
except ValueError:
print('\n'.join(str(float(i)*2) if i.isdigit() else i for i in wordList)