Changing inputs into titles, issue with handling raw spaces - python

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')

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"

The catch_error_str function isn't catching errors when the input is a integer. - Python

Please don't be too harsh because I'm new to coding. The problem I'm having is that the function catch_error_str does not work. For example, when I enter "2" as an input then it says last_name is 2 instead of catching the error.
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
def surname ():
print("What is the surname of the lead booker ")
last_name = catch_error_str()
print(last_name)
print("Welcome to Copington Adventure Theme Park's automated ticket system\nplease press any button to see the ticket prices.")
enter = input()
print("\nAdult tickets are £20 each \nChild tickets are £12 each \nSenior citizen tickets are £11 each")
surname()
Python don't have a problem to covert a number to a string and because of that, there is no error rasing.
You can try
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
if not string.isalpha():
raise ValueError
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
The isalpha() method of string will check if the input not containing numbers and if so it will raise the value error.
The value that is returned from Input() is of type str therefore, the conversion won't generate an error that you can catch with ValueError. Instead you should try to check the type() of the variable. Also, you are requiring the input within the try. I would use something like this:
def catch_error_str():
unvalid = True
while unvalid:
string = input()
try:
string = float(string)
print("You must not enter any numbers")
except ValueError:
unvalid = False
return string
Since floats/ints can be converted to strings without any problem, I'm facing the problem the other way around. I am trying to convert it into a float, if I'm able to, it's because the value is numeric, hence the error. If I am not able to, then that means it will generate ValueError because it is text
Input returns a string even if the user input is a digit.
name = input(“Enter last name: “)
if name.isdigit():
unvalid = True
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
https://docs.python.org/3/library/functions.html#input

user input can only be alphabetical characters and includes spaces

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()

Python: How to demand a string as input rather than a specific value

For the YourName input() I would like to get a value that's a string. Hence, it shouldn't be a float, int, etc. In this example I would like to replace "Sunny" with any value that's a string to make the while loop accept the input.
YourName = ''
while YourName != "Sunny":
print("Please type in your name")
YourName = input()
print(YourName + " is correct")
Thanks in advance, best
Sentino
As mentioned in the comments you could use something similar to the following:
YourName = input("Please enter your name: ")
while True:
if YourName.isalpha():
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
isinstance() is a built-in function that checks to see if a variable is of a specific class, e.g. isinstance(my_var, str) == True. However, the Input() function always returns a string. Thus, if you want to make sure the input was all letters you want to use .isalpha(). You could also use Try/except. As #SiHa said this SO question has a great response.
As pointed out in the comments, this answer will not work if there is a space in the string. If you want to allow multiple name formats you can use Regex. for example you can do the following:
import re
YourName = input("Please enter your name: ")
while True:
if re.fullmatch(r"[a-zA-Z]+\s?[a-zA-Z]+", YourName) is not None:
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
Using Regular Expressions will give you more control on the inputs than regular string methods. Docs, Python Regex HOWTO. re is a standard library that comes with python and will give you the most flexibility. You can use regex101 to help you test and debug.
What the re.fullmatch() will return a match object if found and None if not. It says the input can be any lower or uppercase letter with an optional space in the middle followed by more letters.
If you don't want to import a package then you can loop through your input object and check to see if all characters are a space or alpha using:
all([x.isalpha() | x.isspace() for x in YourName])
however this will not say how many spaces there are or where they are. It would be optimal to use Regex if you want more control.
It's possible that you're using Python 2.7, in which case you need to use raw_input() if you want to take the input as a string directly.
Otherwise, in Python 3, input() always returns a string. So if the user enters "3#!%," as their name, that value will be stored as a string (You can check the type of a variable by using type(variable)).
If you want to check to make sure the string contains only letters, you can use the method isalpha() and isspace() (in my example code, I'll assume you want to allow spaces, but you can exclude that part if you want to require one word responses).
Because these methods operate on characters, you need to use a for loop:
YourName =""
while YourName is not "Sunny" or not all(x.isalpha() or x.isspace() for x in YourName):
#You can pass a string as a prompt for the user here
name = input("please enter name")
print (YourName)
However, I should note that this check is totally redundant since no string containing a non-letter character could ever be equal to "Sunny".
As others have pointed out, input() always returns a string.
You can use the str.isalpha method to check the character is a letter.
YourName = ''
while True:
print("Please type in your name")
YourName = input()
failed = False
for char in YourName:
if not char.isalpha():
failed = True
if not failed:
break
Example:
Please type in your name
> 123
Please type in your name
> John1
Please type in your name
John
John is correct

Symbol-only string detection

I'm fairly new to Python (and programming in general), so I often end up facing really silly issues, such as the one below.
What I want is to repeatedly check if all the characters in a user input are symbols. When such an input is entered, I want to print that string.
Since there doesn't seem to be a way to specifically test for symbols, I decided to test for letters first, and then for numbers, and if both of them come up as negative, then it should print the text.
Here is my code:
while True:
symbols = input("Enter symbol string:")
if symbols == symbols.isalpha():
print (symbols.isalpha())
elif not a == a.isalpha():
print (a.isalpha())
break
Symbols is a little vague but here is a strategy:
symbols = input("Enter symbol string:")
valid_symbols = "!##$%^&*()_-+={}[]"
has_only_symbols = True
for ch in symbols:
if ch not in symbols:
has_only_symbols = False
break
if has_only_symbols:
print('Input only had symbols')
else:
print('Input had something other than just symbols')
The above code first creates a list of symbols which you want to ensure the string is created out of called valid_symbols. Next it creates a variable called has_only_symbols that holds a value of True to begin with. Next it begins to check that each character in the input string exists in valid_symbols. If it hits a character which is invalid then it changes the value of has_only_symbols to False and breaks out of the for loop (no need to check the rest of the string). After the loop is done it checks whether has_only_symbols is True or False and does something accordingly.
Also as a side not, some of your code is not doing what you think it is:
if symbols == symbols.isalpha():
...
will test if symbols, your input string, is equal to the result of symbols.isalpha() which returns a boolean True or False. What you probably meant is just:
if symbols.isalpha():
...
The elif statement is strange as well. You have begun referencing some variable called a but you do not have it defined anywhere in the code you posted. From your description and code it seems you meant to have this elif statement also reference symbols and call the isdigit method:
if symbols.isalpha():
...
elif symbols.isdigit():
...
else:
...
However this is not logically complete as a string with mixed letter, digit, and symbol will slip through. For example abc123!## will fail both the tests and get printed. You want something more exclusive like the above code I have written.
This is how i solved it..
import re
def start():
global count
for letter in SYMBOLS:
if re.search(reg,SYMBOLS):
count=count+1#just to count how many exist
global S#if you want to store the result
S=letter
else:
print(letter,': is not a symbol')
count = 0
SYMBOLS= input('Enter text\n')#INPUT
reg =('[#_!#$£%^&*()<>?/\|}{~:]')#SYMBOL SEARCH
start()
Slightly updated version of Farmer Joe's code. Better processing of input included.
symbols = input("Enter any characters:")
valid_symbols = "!##$%^&*()_-+={}[]"
if symbols == '':
print("None of characters have been entered. Please try again")
else:
for ch in symbols:
if symbols.isalnum() is True:
print('No symbols have been detected in the input')
break
else:
if ch not in valid_symbols:
print('There are symbols mixed with other characters')
break
else:
print('Your input contains symbols only')

Categories