我在“数据结构”类中有一个作业,并且正在使用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
>>>
所以我的问题是弄清楚如何提取数值,然后将其加倍。我不知道从哪里开始。
任何反馈总是很感激。谢谢!
在这儿:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句