Jake Jackson
Jake Jackson

Reputation: 1225

How do I check the user has entered two or more words in a single string?

My function takes a string, and as long as the string has two names in it, such as "John Smith", the program runs OK.

My issue occurs when the user enters 1 or less names in their input.

user_input = input("Enter your name: ")

name = user_input.split()

print(name[0])
print(name[1])

Ideally, it would check that the user has entered a string of just two names, but it doesn't really matter.

I don't know the required checks in Python; if it was Java, it would be a different story.

Upvotes: 1

Views: 1328

Answers (2)

user498823
user498823

Reputation: 65

user_input = input("Enter your name: ")

name = user_input.split()

for x in names:
    print(x)

Upvotes: 0

Jan
Jan

Reputation: 43169

You could use len() or try/except as in:

user_input = input("Enter your name: ")
if len(user_input.split()) > 1:
    print("At least two words.")
else:
    print("Only one word")

Or

user_input = input("Enter your name: ")
try:
    user_input.split()[1]
    print("At least two words.")
except IndexError:
    print("Only one word")

Upvotes: 3

Related Questions