0

I want users to enter random words/numbers/phrases. If they have entered more then 5 then they get an error message and if the enter 5 or less then I print out the list vertically. I don't know what code to use so that it does not count the white spaces. As well, I want to count the number of words/numbers, NOT the amount of characters. If you could just take a look at my code and give some help, that would be great!

myList = [] 

myList = raw_input("Enter words,numbers or a phrase (a phrase should be entered between two quotations)...")

if len(myList) > 5:
print('Error')

else:
#print output
for variable in L:
    print variable

2 Answers2

1

Try something like this using str.split() to return a list of the words in the string using the default delimiter of a space character:

myList = []

while(True):
    myList = raw_input("Please enter words or numbers: ")
    if(len(myList.split())) <= 5:
        break
    else:
        print("Error: You entered more than 5 arguments, Try again...")

for item in myList.split():
    print(item)

Try it here!

martineau
  • 119,623
  • 25
  • 170
  • 301
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

The working code for what you want is the following:

# I separate the input text by the spaces
data = raw_input("Enter something... ").split(" ")

# handle the data
if len(data) > 5:
    print("Only 4 or less arguments allowed!")
else:
    for variable in data:
        print(variable)

Now, this doesn't prevent the user from inserting other characters like !, $%"#$, so to handle that case, you should check for some of the answers in this question: Stripping everything but alphanumeric chars from a string in Python

Have fun!

Community
  • 1
  • 1
XzAeRo
  • 566
  • 5
  • 11
  • ok great. Also, if I want to use phrases like "hello world" and want it to count as one, will this work as well? – user3093377 Jan 10 '17 at 20:42
  • If you want that behaviour make your user input words separated by commas and use `split(",")` – Zan Jan 10 '17 at 21:16