I am trying to return a yes or no answer to show whether the string has spaces or letters. The bolded part is the part I need to get right. I got the other parts...
Here is what I have put and it doesn't work out correctly...
if (string.isalpha() and string.isspace()):
print('Only alphabetic letters and spaces: yes')
else:
print('Only alphabetic letters and spaces: no')
How can I use them together? I know how to do this separately but not together. I know this may seem really simple but I am a beginner.
example of the program----
Enter a string: please open my email
Length: 20
First character: p
Last character: l
Contains open: yes
Only alphabetic letters and spaces: yes
Only numeric digits: no
All lower case: yes
All upper case: no
You're testing the whole string. You should be testing each character individually.
is_alpha_or_space = all(c.isalpha() or c.isspace() for c in string)
You can use or and all to check each letter:
if all(char.isalpha() or char.isspace() for char in string):
print('Only alphabetic letters and spaces: yes')
Two options:
if all(x.isalpha() or x.isspace() for x in original):
or
original.replace(' ','').isalpha()
should work.
You can try changing the condition to str(input.isspace() and input.isalpha())
Related
I have this code:
print('abcdefg')
input('Arrange word from following letters: ')
I want to return True if the input consists of letters from the printed string but it doesn't have to have all of printed letters.
That's a perfect use case for sets especially for set.issubset:
print('abcdefg')
given_input = input('Arrange word from following letters: ')
if set(given_input).issubset('abcdefg'):
print('True')
else:
print('False')
or directly print (or return) the result of the issubset operation without if and else:
print(set(given_input).issubset('abcdefg'))
This sounds a little like homework...
Basically you would need to do this: Store both strings in variables. e.g. valid_chars and s.
Then loop through s one character at a time. For each character check if it is in valid_chars (using the in operator). If any character is not found in valid_chars then you should return False. If you get to the end of the loop, return True.
If the valid_chars string is very long it would be better to first put them into a set but for short strings this is not necessary.
Im trying to use regex do check a variable for accepted letters and numbers. This is my def:
def special_match(strg, search=re.compile(r'[a-z0-9]').search):
if bool(search(strg)) is True:
print ('Yes: ' + strg)
elif:
print ('nej: ')
while 1:
variabel = raw_input('Enter something: ')
special_match(variabel)
sys.exit()
And it seems that is accepts not allow symbols in combination with allow symbols:
Enter something: qwerty
Yes: qwerty
Enter something: 1234
Yes: 1234
Enter something: !!!!
nej!
Enter something: 1234qwer!!!!
Yes: 1234qwer!!!!
Enter something:
The last one should not be accepted.. What I'm doing wrong??
All your regular expression search is doing is checking to see if at least one of the characters is present.
If you want to require that the entire string contains nothing but those characters, then you can use:
r'^[a-z0-9]*$'
That anchors the pattern at both the start and end of the string, and only matches if all of the characters in between are in the specified set of characters.
Note that this will also match the empty string. If you wish to require at least one character, then you can change the * to +.
the search method finds for regex you gave and if it finds then returns a Match object here 1234qwer!!! has [a-z0-9] but !!!! doesnt.
Try a!!!. that will also return True.
You could try doing
re.search(r"[^a-z0-9]",word)
and if this returns True that means your word has something other than digits and alphabets and that should be rejected.
NOTE: ^ means not.
The only thing that regex does is check that there is a number or a letter in your string. If you want to check that it only has numbers and letters, you need to anchor your pattern at the start and end, and add a repeat: r'^[a-z0-9]+$'
Note though that there is no need to use regex for this: the string isalnum() method will do the same thing.
There are a couple of other odd things in your code; you should definitely not be compiling a regex in the function signature and passing on the resulting search method; also you should not be converting the result to bool explicitly, and you should not compare bools with is True. A more Pythonic version, assuming you wanted to stick to the regex, would be:
def special_match(strg, search=None):
if not search:
search = re.compile(r'[a-z0-9]').search
if search(strg):
print ('Yes: ' + strg)
else:
print ('nej: ')
Also note elif is a syntax error on its own.
I'm having trouble getting my input to accept only a-z and A-Z letters. This is what I came up with
while(not(studentName == "END")):
studentName = input("What is the name of the student (END to finish) ")
if not re.match("^[a-z]*$", studentName):
print("Only letters are allowed")
elif len(studentName) == 0:
print("Insufficient characters. Please try again.")
else:
studentsNames.append(studentname)
However I just come up with an error "re not defined".
What do I do :C
Instead of using regular expressions, I like to use the built-in string methods. One of these is str.isalpha(), which, when called on a string, returns True if the string contains only A-z. So instead of:
if not re.match("^[a-z]*$", studentName):
print("Only letters are allowed")
I'd just write:
if not studentName.isalpha():
print("Only letters are allowed!")
You need to import re module and you must need to change your regex as,
if not re.match(r"^[A-Za-z]+$", studentName):
Just type the below code at the top of your python script.
import re
Your regex "^[a-z]*$" would match zero or more lowercase letters. That is, it would match empty strings also and it won't match the string with only uppercase letters like FOO.
So this if not re.match("^[a-z]*$", studentName): will return true for all the strings which must not be an empty string or the string which contains only lowercase letters.
You could use a set, and string.ascii_letters:
from string import ascii_letters
def is_all_characters(student_name):
return set(student_name) in set(ascii_letters)
isalpha() works for this requirement.
username = input("Enter Username: ")
if username.isalpha() is False:
print("Only Text allowed in Username")
else:
print("Welcome "+username)
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.
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()