Vladislav Reshetnyak
Vladislav Reshetnyak

Reputation: 321

Break the sentence into words using the space character as a delimiter in Python

I have an assignment in my Data Structures class and I am using Python to try to solve it. I am really stuck and rusty in Python so please bear with me.

Problem

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.

My Code so far...

import string
import re

def main():
  string=input("Input a sentence: ")
  wordList = re.sub("[^\w]", " ",  string).split()
  print("\n".join(wordList))
main()

This gives me this output:

>>> 
Input a sentence: I like to eat 7 potatoes at a time
I
like
to
eat
7
potatoes
at
a
time
>>> 

So my problem is figuring out how to extracting the numeric value and then doubling it. I have no clue where to even begin.

Any feedback is always appreciated. Thank you!

Upvotes: 3

Views: 1521

Answers (2)

TerryA
TerryA

Reputation: 60004

At here:

print("\n".join(wordList))

You can use a list comprehension to determine whether the word is a number or not. Maybe something like:

print('\n'.join(str(int(i)*2) if i.isdigit() else i for i in wordList)

This finds strings that appear to be integers by using str.isdigit, converts it to an integer so we can multiply it by 2, and then turn it back into a string.


For floats, then a try/except structure is helpful here:

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)

Upvotes: 2

kojiro
kojiro

Reputation: 77137

Just try to cast the value to a float. If it fails, assume it's not a float. :)

def main():
  for word in input("Input a sentence: ").split():
      try:
          print(2 * float(word))
      except ValueError:
          print(word)

The above will still print 7.0 instead of 7, which is not strictly to spec. You can fix this with a simple conditional and the is_integer method to float.

Upvotes: 4

Related Questions