user input can only be alphabetical characters and includes spaces - python

I am looking to ask the user to input their first and last name and validate it so that it is only alphabetical letters and spaces and then add it to a text file.
**This is the edited code from your suggestions and it always returns the first print message even though letters have been entered
while True:
new_Book_AuthorFName = input('Enter Author First Name: ')
new_Book_AuthorLName = input('Enter Author Last Name: ')
new_Book_Author_Name = new_Book_AuthorFName + " " + new_Book_AuthorLName
try:
new_Book_Author_Name.replace(' ', '').isalpha()
print("Please Only Use Alphabetical Characters in Name.")
continue
break
except ValueError:
print("Invalid Name.")

Something like this should work:
def include_letter_and_spaces_only(string):
return "".join(string.split(" ")).isalpha()
And then use as:
include_letter_and_spaces_only("test Test Test") # True
include_letter_and_spaces_only("test 12 Test Test") # False

I would do this as.
def lettersOnly(theString: str) -> bool:
"""Determine if a string only contains letters and spaces or not."""
return ''.join(
theString.split(' ')
).isalpha()

Simplest and most pythonic way to be:
def is_alpha_and_spaces_only(string):
return string.replace(' ', '').isalpha()
Faster and more efficient than KetZoomer's approach as it does not require you to (a) split string & (b) combine it back to have result.
P.S. Or just the spirit of the function if you dont want to define that. Just use new_Book_Author_Name.replace(' ', '').isalpha() inplace of if not new_Book_Author_Name.isalpha()

Related

How to check if string contains only valid amount of spaces

I need to write code that checks if a certain input string is valid. It must:
Contain a "space" in the input string which separates words
Not contain multiple consecutive spaces in a row
Not contain just a "space" (just
single space as an input).
Here is what I mean:
username = str(input())
print(username)
username = "two apples" # acceptable
username = "two apples and pears" # acceptable
username = "two' '' 'apples" # not acceptable (because of 2 spaces in a row or more)
username = " " # not acceptable (because of single space with no other words.)
username = "' '' '' '' '' '' '" #not acceptable because of multiple spaces (didn't know how to type it in here better to clarify.
I recognize that this might be slightly different than what you are directly asking for, but why not strip the extra spaces from the username input? You could use regex to quickly strip them out per this answer.
If you simply want to return an invalid input, I would again use regex.
import re
username = str(input("Please enter your username: "))
if re.search(" {2,}", username):
print("Please do not include multiple spaces in a row in your username!")
else:
# Do the rest of your program.
I was having my online class, so I couldn't do on time. Now I can give the the answer.
Here's the code. It's pretty simple to understand too.
username = input()
if (" ") in username:
print("Eh!")
elif username.isspace():
print("Ew!")
else:
print(username)
And BTW you don't need to use str() in the input as it takes a string input by default.
Here is the code you are looking for I believe. Please test with different test cases and comment if something is wrong. I tried with all your test cases.
def checkspace(string):
if string:
for idx,i in enumerate(string):
try:
if (string[idx] == ' ' and string[idx+1] ==' '):
return 'String is Not Perfect'
except:
return 'String is Not Perfect'
print('String is Perfect')
else:
return 'No String At AlL'
Eg:
string="two apples"
checkspace(string)
output:
"String is Perfect"
Eg:
string="two apples"
checkspace(string)
output:
"String is Not Perfect"

Need help on solving an issue with some code for my class

I need to create a program for my python instructor that processes a name and outputs it in the format "Last, First". The 2 different ways the user can input their name are, "first last"(no comma), or "last, first".
I've used my Python book but it does not help much when it comes to what the instructor wants from us to create.
space = name.index(' ')
first = name[0:1].upper()+name[1:space]
comma = name.index(',')
last = name[0:1].upper()+name[1:comma]
print(last + ', ' + first)
The correct result of this program should be "Last, First" as I stated already above. I keep getting the first name entered and the output is "name, name," (name is whatever is being inputted into the input statement)
example.) user input --> 'joe bob'
output --> 'Joe, Joe,'
The mistake you did was first and last were assigned the same string.
I would suggest doing something like this:
name = 'Bob, joe'
if ',' in name:
last, first = name.split(',')
else:
first, last = name.split(' ')
print(last.strip().capitalize() + ', ' + first.strip().capitalize())
Hope this helps.
You can do something like this:
name = input("Write a name: ")
space_idx = name.index(' ')
if "," in name:
print(name)
else:
name = name[space_idx+1:] + ", " + name[:space_idx]
print(name)
In Python3, you can use the split() method to convert a string into a list of words, separated by spaces.
This can be done by words = name.split().
Now, assuming that you have already learned string manipulation, you can remove the comma from the end of the first name (if there is), the first word in the words list.
Then, simply print the list for first name and last name.
Good luck!
So the simplest way is to user rstrip and split function
getting the value in list and print it from index number
name = list(map(str, input().rstrip().split()))
print(name[1], name[0])
print(name[1] + ', '+ name[0])
Input
Firstname Lastname
OutPut
Lastname Firstname
lastname, Firstname

using try and regex in python

I'd like to use a try/except statement for checking that a string consists of letters only.
What is wrong with the following
class LetterError(Exception):
pass
name = ""
while name=="":
try:
x = re.match(r'[a-zA-Z]',(input("Please enter a name: ")))
raise LetterError
except LetterError :
print("Insert letters only")
Your regex [a-zA-Z] will match only one character out of given range [a-zA-Z].
I suppose by name you mean multiple characters. Thus use [a-zA-Z]+ for matching multiple characters.
You are raising error in all case. You need to add a condition and also, you don't need your custom error. Regex from here https://stackoverflow.com/a/3617808/5567387
name = ""
while name == "":
name = raw_input("Please enter a name: ")
is_valid = re.match(r'^[a-zA-Z]+$', name)
if not is_valid:
name = ""

check user_input with if token in a loop

I am trying to write a function that checks my input to see whether I have entered the character '?'.
This is what I got so far:
def check_word():
word = []
check = 0
user_input = input('Please enter a word that does not contain ?: ')
for token in user_input.split():
if token == '?':
print('Error')
check_word()
My input: hello?
It is supposed to show 'Error'. But it doesn't show anything. Could you please tell me what wrong it is in my code.
I would use the in operator to do this
def check_word(s):
if '?' in s:
print('Error')
For example
>>> check_word('foobar')
>>> check_word('foo?')
Error
The problem is how you split the string of the user_input.
user_input.split():
The example doesn't contain whitespaces so the condition isn't met. If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces.
But for this example you have two choices:
1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ?.
That is, change user_input.split(): into simply user_input without splitting. This option is good if you might ever want to add some sort of action for each char.
2) It's very easy just to use in, like this:
if '?' in s:
print('There is a question mark in the string')
This is a very simple solution that you can expand and check for other chars in the string as well.
It's because user_input.split() splits the user_input by whitespace. Since hello? does not contain any whitespaces, token is equal to your input and the loop is executed once.
You should iterate over user_input instead, or simply check if '?' in user_input.

Changing inputs into titles, issue with handling raw spaces

so I'm quite new to programming and I'm trying to learn python as a starter.
I'm trying to make a function that does multiple things (I'm going to use it for limiting inputs on names).
Rejects purely numerical inputs
Rejects inputs made purely of spaces
Rejects null inputs
Changes the input into a title
def debugstr(inputa):
inputa = inputa.replace(" ", "")
try:
int(inputa)
inputb = debugstr(input("Invalid input, please enter Alphabetic strings only: "))
except:
if inputa == "":
debugstr(input("Invalid input, please enter Alphabetic strings only: "))
else:
return inputa.title()
The issue that I have is that the code will only reject blank inputs on the first try when running the function, if something is rejected once and the user inputs a series of spaces again, then it will just accept it as an input.
Thanks for your time in advance! It's very appreciated :D
A more natural way of handling this (without calling the same function from within itself) is:
def make_title():
def get_user_input():
return input('Enter an alphabetic string: ')
while True:
s = get_user_input()
s = s.strip()
if not s:
print('blank input!')
continue
if s.isdigit():
print('contains only digits!')
continue
return s.title()
print(make_title())
Some notes:
Try not to repeat yourself (e.g. the duplicated error message in your code)
Python contains many useful string methods and s.isdigit() returns True if s contains only numbers
You can strip the whitespace from your input with s.strip() and if you're left with the empty string, '', if not s will be True (the empty string is equivalent to False.
In python 3, you can use isinstance to check if an object is a string.
word = input("Enter string: ")
def checkString(s):
if isinstance(s, str):
print('is a string')
elif not s:
print('empty')
else:
print('not a string')

Categories