How to check if every character of the string is different? - python

I was just wondering, how to check if I ask a person to input a string, how do I check if every character inside that string is different?
For an example:
string = str(input("Input a string: ")
I would like to do it with a while loop. So, if two characters in a string are different, it stays in the loop and prompts the user to input the string again.

If I understand your question correctly, you want to reject any string that contains more than one copy of the same character. If a string with duplicated characters is entered, you want to repeat the prompt and get another input.
The easiest way to do the duplicate check is to create a set from your string and then check if the set has the same length as the original. If there were any duplicates in the string, they'll be present only once in the set.
while True:
input_string = input("Enter a string")
if len(set(input_string)) == len(input_string):
break
print("Please avoid repeating any characters")

You could also try this:
while True:
b = input("Enter a string: ")
if all([b[i] not in b[:i] + b[i+1:] for i in range(len(b))]):
break
print("Please try again!")

Related

Username and Password validation with user input

Im very new to python and I am creating a user login system, I am currently on a bit of creating a username and password with user input that must meet some conditions e.g
username:
Cannot contain any spaces
Must be at least 5 characters
Cannot include special characters
Your system must display a message to the user telling them what they did wrong if they did not meet
one or more of these criteria (so you will need at least 4 error messages).
My code is as below, but surely theress a better way to do this?
while True:
sNewUser1 = input("""Please enter a new username.
The username must NOT contain any spaces, it must have at least 5 characters and
it cannot include any special characters: \n\n""")
if len(sNewUser1) < 5:
print("Your username is too short, please enter 5 or more characters! Please try again!\n")
elif sNewUser1.count(" ") > 0:
print("Your username contains one or more spaces, this is not allowed! Please try again! \n")
elif sNewUser1.isalnum() == False:
print("Your username contains a special character please try again! \n")
else:
greetuser()
break
while True:
sNewPass1 = input("""\n\nPlease enter a new password.
It must contain:
At least one Capital letter
At least one lower case letter
At least one special character
It has to be at least 6 characters in length:\n\n""")
if len(sNewPass1) < 6:
print("Your username is too short, please enter 5 or more characters! Please try again!\n")
Input prompts can be shortened and more direct.
The whole code should be wrapped in a main() function which is called at the end using the if __name__ == "__main__" condition. This is a convention.
Use is with boolean values, in those conditional statements.
Use the snake_case naming style.
The long strings can be broken into multiple smaller ones.
By now, linters and code-formatters (even Pylint) will not complain about anything.
Your complete code may look something like this, although there is still room for improvement:
"""This is a program for validating usernames and passwords"""
def main():
"""This is the main function"""
while True:
new_user_1 = input("\nPlease enter a new username. "
"It should be at least 5 characters long "
"and not contain spaces or special characters: ")
if len(new_user_1) < 5:
print("Your username is too short. Please try again: ")
elif new_user_1.count(" ") > 0:
print("Your username contains spaces. Please try again: ")
elif new_user_1.isalnum() is False:
print("Your username contains a special character. "
"Please try again: ")
else:
# call another function
break
while True:
new_pass_1 = input("\nPlease enter a new password. "
"It should be 6 characters long "
"with atleast one uppercase letter, "
"one lowercase letter, and one special character: ")
if len(new_pass_1) < 6:
print("\nYour password is too short. Please try again: ")
elif any(lower.islower() for lower in new_pass_1) is False:
print("\nYour password does not contain lowercase letters. "
"Please try again: ")
elif any(upper.isupper() for upper in new_pass_1) is False:
print("\nYour password does not contain uppercase letters. "
"Please try again: ")
elif any(digit.isdigit() for digit in new_pass_1) is False:
print("\nYour password does not contain digits. "
"Please try again: ")
elif any(not char.isalnum() for char in new_pass_1) is False:
print("\nYour password does not contain special characters. "
"Please try again: ")
elif new_pass_1.replace(" ", "") != new_pass_1:
print("\nYour password contains whitespaces. "
"Please try again: ")
else:
# call another function
break
if __name__ == "__main__":
main()
Edit: The previous answer had some bugs. The new one works as intended:
Strings were broken down into smaller ones, but spaces in the end were ommitted.
Simple for loops were used, which checked whether the whole string was uppercase, lowercase, digits, special characters or not, instead of checking each character in the string. The new code fixes this with the use of a built-in function called any. From Python's official documentation:
any(iterable):
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
Here is an explanation of why/how this works:
elif any(lower.islower() for lower in new_pass_1) means: for any lower in new_pass_1, if lower.islower() returns True, then: code goes here. Therefore, it returns True if any character in the string is lowercase. So if it returns False, it would mean that it did not find any lowercase character in the whole string. The same applies to the checks for uppercase letters and digits.
elif any(not char.isalnum() for char in new_pass_1) means: for any char in new_pass_1, if char.isalnum() does not return True (i.e. the char is a special character), then: code goes here. Therefore, it returns True if any character in the string is a special character (i.e not an uppercase letter, lowercase letter or digit). So if it returns False, it would mean that it did not find any special character in the whole string.
If you're confused about not char.isalnum(): any_string.isalnum() checks whether any_string is alphanumeric or not, i.e whether it is made up of alphabets and numbers only. So inverting it with not char.isalnum() would now check whether any_string is not alphanumeric. And we know that if something is not alphanumeric, it is a special character. Note that this will consider whitespaces to be special characters as well, so I've added a final if statement to check for whitespaces.

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

How to check if user input is a string

I have two user inputs: in the first one user has to insert a text what is string type and in the second one to insert a number what is int type.
I used try/except ValueError, so user couln't insert a string where int is needed. Although ValueError wouldn't work when user inserts int where string is needed.
How can input value be false, when int is inserted, where str is asked?
This is my code now:
while True:
try:
name_input = input('Insert name')
name = str(name_input)
number = input('Insert number: ')
num = int(number)
except ValueError:
print('Wrong')
If you would like the whole name to be alphabetic you can simply add an if statement like this:
if not name.isalpha():
print("wrong, your name can only include alphabetic characters")
Or better fitting your short example:
if not name.isalpha():
raise ValueError
This will only accept input strings that don't contain any number at all.
If you would like to allow digits in your name as long as the name begins with a letter you could also have something like the following:
if len(name) < 1 or not name.isalnum() or not name[0].isalpha():
raise ValueError
This checks first whether the name is at least 1 character long, then it checks whether the whole name consists solely of alphabetic characters and numbers, followed by a final check to see if the first character is an alphabetic character.
A string with a number in it is still a valid string - it's a string representing that number as text.
If you want to check that the name is not a string composed just of digits, then the following code will work:
while True:
try:
name = input('Insert name: ')
if name.isdigit():
raise ValueError

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.

Getting an input that does not have any whitespace - python

So, this functions is supposed to get a guess from a user. This guess should be one character and does not have any whitespaces in it.
The problem is, when I enter one space ' ' it returns 'You must enter a guess'. However, when I enter 2 spaces ' ' it returns 'You can only guess a single character'.
I need it to display 'You must enter a guess' instead. Whether the input contained one space or two or tap or two or even mix with tap and spaces. How can I do that?
def get_guess(repeated_guess):
while True:
guess = input('Please enter your next guess: ') # ask for input
guess.strip() # remove all spaces
guess = str(guess).lower() # convert it to lowercase string
if len(guess) > 1: # check if it's more than one character
print('You can only guess a single character.')
elif guess.isspace(' '):
print('You must enter a guess.')
elif guess in repeated_guess: # check if it's repeated
print('You already guessed the character:', guess)
else:
return guess
guess.strip() returns the stripped string; guess remains unchanged. You need to reassign it:
guess = guess.strip()
An easy way without regex.
guess = ''.join(guess.split())
This removes whitespace from anywhere in the string. strip only removes from the ends of the string until the first non-whitespace character.
You should put the guess new value after you strip it
guess=guess.strip()
Your problem is that you check the length of the string before checking if it is only white space. A string with 2 spaces will be considered a 2 character string, and since that if statement will be evaluated first it returns the multi character print statement.. If you reorder the code so that it checks if the string is only white space first it will instead prioritize that print statement over the other.
I'm not sure that I fully understand your question but, but I'll take a stab.
If you are looking for the user to input a single character as an input (that doesn't include white spaces), you should strip all of the white spaces from the input. guess.strip() only removes the leading and trailing whitespaces.
Try using guess.replace(" ", ""); this will remove all whitespaces from the user input.
Also, like others suggested, these methods return a new string with the appropriate characters stripped. Your code should look like guess = guess.strip()

Categories