How to check if input is text [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
Hi all I am pretty new to python coding but have recently stumbled upon a problem, when asking people for names the program will allow numbers, is there a simple way to fix this.
My code is something like this:
print("what is your name?")
name=input()
print("thank you",name,".")
I am not entirely sure that is the exact code but it does those three things. Thank you and sorry it is a bit basic. Also I am using 3.3.2 I think.

You can use str.isalpha to test if a string is all alphabetic characters (letters):
>>> 'abcde'.isalpha()
True
>>> 'abcde1'.isalpha()
False
>>>
If you have a specific character set to test for, you can use all and a generator expression:
chars = set('abcde') # Put the characters you want to test for in here
all(c in chars for c in name)
Also, I used a set instead of a regular string of characters to improve efficiency. Sets have O(1) (constant) complexity with in where as strings have O(n) (linear) complexity. In other words, it is faster to find things in a set than in a string.
Lastly, you can use string.ascii_letters instead of typing out the whole alphabet:
>>> from string import ascii_letters
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>
This becomes especially useful if you want to test for all the letters of the alphabet plus another character or so (such as a hyphen):
chars = set(ascii_letters + '-')

There are a couple of ways to address this. One would be to do something like
if name.isalpha():
# it's alphabetic
else:
# it's not - prompt for new input
But this will reject some names that you might like, such as "John Smith" or "Kate O'Conner".
A more careful approach would be something like
if any(map (lambda c: c.isdigit(), name)):
# there's a digit in there, reject it
else:
# it's got no digits, but maybe it still has punctuation that you don't want?
# do further checks as needed
You can also build a whitelist:
import string
allowed_chars = string.ascii_letters+"'"+ "-" + " "
# allow letters, single-quote, hyphen and space
if all([c in allowed_chars for c in name]):
# passes the whitelist, allow it

Related

Isspace function in python

I'm having trouble trying to execute this code, I want the user to input a value, the program checks if that value is a string then it returns the length.
If the value contains whitespaces the programs remove the whitespace and print the length.
But if it contains any integer values the program returns "No Integers is Allowed"
This is the code:
def length(Name):
long = len(Name)
return long
new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if value1.isspace() == True:
print("This is Before Removing Spaces: " + value1)
value2 = value1.replace(" ", "")
print("This is After Removing Spaces: " + value2)
elif value1.isalpha() == True:
print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
print("Integers are not allowed! ")
else:
print("There's someting wrong with "+ value1)
So if you can help me with that I appreciate it.
Thanks
I don't think the str.isspace, str.isalpha and str.isdigit methods do what you expect them to do. To start with, they all test if all the characters in the string you enter are of the type that is described in their name. Your code seems to be expecting them to be return True if any of the characters match. That is, if there are any spaces, you want to remove them and show the two lengths, before and after.
There's no single string method that will do that test for you in Python. You could use regular expressions (which are more powerful, but much more complicated), or you could write some slightly more elaborate code to do the test. I'd suggest using the any function, and passing it a generator expression that calls the method you want on each character in the string.
if any(c.isspace() for c in user_str):
...
This may not be exactly what you want for all of your tests. The desired logic of your code is not entirely obvious, as there are a number of corner cases that your output doesn't specifically address. Is a string that contains both letters and numbers valid? How about one that has spaces in between numbers, but no letters at all? You may need to reorder the conditions of your if/elif/else statements so that they match what you intend.
I'd also note that the variable name you used for user input, new_length, is very misleading. It's not a length, its the string you want to measure the length of! It's a lot easier to make logic errors about variables that have misleading or unclear variable names, so taking time to go back and reconsider names you chose earlier is sometimes a good idea, as it can improve the clarity of your code a lot! Descriptive variable names are good, but it's a tradeoff between clarity and brevity, as long names are tedious to type (and prone to typos). They also can lead to line length issues, which can make it less convenient to see all your code on your editor screen at once.
You can use this function to check if the input string contains a number:
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
It returns true if there is a number and false if there is not.
As for the whitespaces you can ommit isspace(). Using replace() alone will do the job, even if there are no whitespaces.
stri='jshsb sjhsvs jwjjs'
stri=stri.replace(' ','')
I suggest reading the documentation in these cases. For isspace, note here that
Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.
That is, if there's anything that's not a space there, it will be False. Which is annoying, but why check in the first place? Just do the replacement! If there's no whitespace, it won't do nothing. If you need to print those statements, you can do
if ' ' in value1:
...
(of course, this doesn't consider all the possible kinds of whitespaces, check the other answers for doing the for loop if you need that)
Next, I believe you need to remove the elifs and just use if statements, since note that if you input a name with a space, it will print the name with the spaces removed... and nothing after that. Not even if it has integers in it. This is because elif statements don't execute once another above them did.
There are many other things you need to consider, but these two I think you should consider first. Hope it's useful!
You can use the re module in Python to check for white spaces in your string. It returns True if there are white spaces and False otherwise.
import re
def length(Name):
long = len(Name)
return long
new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if re.search('\s', value1):
print("This is Before Removing Spaces: " + value1)
value2 = value1.replace(" ", "")
print("This is After Removing Spaces: " + value2)
print("Here is The Length: ", length(value2))
elif value1.isalpha() == True:
print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
print("Integers are not allowed! ")
else:
print("There's someting wrong with "+ value1)

Testing weither a string input in python contains the correct char in correct format [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 2 years ago.
Sorry if this has been asked before, I can't seem to find the answer anywhere.
So I have a user input for a DNA sequence analysis program, I want to check if the input is in fact a sequence i.e. that it contains A, C, T, G or a, c, t, g.
I have thought of implementing a regular expression where the re.search would return True if the correct format was found. Then if false I can ask for the input again etc. Like so:
input = "ATGGCAAT"
>>True
input = "atg"
>>True
input = "AATG!4"
>>False
input = "this input contains all the char but is in the wrong format"
>>False
I have also considered using a negative look ahead that would match with anything other than the correct format.
But I can't seem to get it right. Any help would be so appreciated! Feel like I'm going around in circles!
You need to check that the string contains ACTG in lower or upper cases and only them, so you anchor the expression at the start and the end of the line:
import re
re.match("(?i)^[ACTG]+$", input)
You can use start and end of string operators, and then specify the characters you want, one or more times, like so:
^[actgACTG]+$
You can find your example here: https://regex101.com/r/CgiTEL/1
Non-Regex solution. This function will check the string and return False if any character doesn't match something in your designated list, otherwise will return True
def test(string_input):
for s in string_input: # loop through each character in the string
if s.lower() not in ["a", "c", "t", "g"]: # lower() to change s to lowercase
return False
else: # if all characters in string pass at end of loop return True
return True
string_input = "AATG!4"
test(string_input)
>> False

How to replace strings with other strings via .replace method in python?

I'm trying to do the following:
Replace any inputted strings, with "HA!". How many they are, is dependent on how many letters there are in the string (three letters means three "HA!"s, etc)
CODE:
stringI = input("Enter anything in here! It will become laughter after
you do this! \n")
if stringI.isalpha:
print(stringI.replace(stringI, "HA!", len(stringI)))
It outputs only one "HA!", regardless of the number of chars in the string.
I agree with the above comments that it's not really necessary to use the replace method because you're really just making a new string. Here's a simple way to do it that's pretty easy to visualize:
>>> count = 0
>>> stringI = input("Enter anything in here! It will become laughter after you do this\n")
Enter anything in here! It will become laughter after you do this
test test
>>> count = 0
>>> for char in stringI:
... if char.isalpha():
... count += 1
...
>>> str_builder = ''
>>> for ha in range(count):
... str_builder += "HA! "
...
>>> str_builder
'HA! HA! HA! HA! HA! HA! HA! HA! '
>>>
I can think of two ways of doing this:
Loop over the string to build a new string, replacing letters with HA!
def make_ha(s):
return "".join(["HA!" if c.isalpha() else c for c in s])
Make a translation table and use that to translate strings
from string import ascii_letters
trans = str.maketrans(dict.fromkeys(ascii_letters, "HA!"))
def make_ha2(s):
return s.translate(trans)
The first is a little simpler to understand, while the second will get complicated less quickly if you start adding other rules later. The later also works only for ascii letters, while the former will operate based on the Unicode definition of an alphabetic character.
print(make_ha("aaBB123")) # HA!HA!HA!HA!123
print(make_ha2("aaBB123")) # HA!HA!HA!HA!123

How can I output a string excluding ALL whitespaces? [duplicate]

This question already has answers here:
How to strip all whitespace from string
(14 answers)
Closed 4 years ago.
Basically, I'm trying to do a code in Python where a user inputs a sentence. However, I need my code to remove ALL whitespaces (e.g. tabs, space, index, etc.) and print it out.
This is what I have so far:
def output_without_whitespace(text):
newText = text.split("")
print('String with no whitespaces: '.join(newText))
I'm clear that I'm doing a lot wrong here and I'm missing plenty, but, I haven't been able to thoroughly go over splitting and joining strings yet, so it'd be great if someone explained it to me.
This is the whole code that I have so far:
text = input(str('Enter a sentence: '))
print(f'You entered: {text}')
def get_num_of_characters(text):
result = 0
for char in text:
result += 1
return result
print('Number of characters: ', get_num_of_characters(text))
def output_without_whitespace(text):
newtext = "".join(text.split())
print(f'String without whitespaces: {newtext}')
I FIGURED OUT MY PROBLEM!
I realize that in this line of code.
print(f'String without whitespaces: {newtext}')
It's supposed to be.
print('String without whitespaces: ', output_without_whitespace(text))
I realize that my problem as to why the sentence without whitespaces was not printing back out to me was, because I was not calling out my function!
You have the right idea, but here's how to implement it with split and join:
def output_without_whitespace(text):
return ''.join(text.split())
so that:
output_without_whitespace(' this\t is a\n test..\n ')
would return:
thisisatest..
A trivial solution is to just use split and rejoin (similar to what you are doing):
def output_without_whitespace(text):
return ''.join(text.split())
First we split the initial string to a list of words, then we join them all together.
So to think about it a bit:
text.split()
will give us a list of words (split by any whitespace). So for example:
'hello world'.split() -> ['hello', 'world']
And finally
''.join(<result of text.split()>)
joins all of the words in the given list to a single string. So:
''.join(['hello', 'world']) -> 'helloworld'
See Remove all whitespace in a string in Python for more ways to do it.
Get input, split, join
s = ''.join((input('Enter string: ').split()))
Enter string: vash the stampede
vashthestampede
There are a few different ways to do this, but this seems the most obvious one to me. It is simple and efficient.
>>> with_spaces = ' The quick brown fox '
>>> list_no_spaces = with_spaces.split()
>>> ''.join(list_no_spaces)
'Thequickbrownfox'
.split() with no parameter splits a string into a list wherever there's one or more white space characters, leaving out the white space...more details here.
''.join(list_no_spaces) joins elements of the list into a string with nothing betwen the elements, which is what you want here: 'Thequickbrownfox'.
If you had used ','.join(list_no_spaces) you'd get 'The,quick,brown,fox'.
Experienced Python programmers tend to use regular expressions sparingly. Often it's better to use tools like .split() and .join() to do the work, and keep regular expressions for where there is no alternative.

Python 3, receive a string as an argument without any return value

I'm learning Python and have been taking an online class. This class was very basic and I am know trying to continue my studies elsewhere. Stackoverflow.com has helped me a great deal. In the online course we didn't cover a lot about return statements, which I am now trying to learn. I would like to do something very basic, so I was thinking of creating a program that would receive a string as an argument without having any return value. I want the user to type a word that will be shown with characters or symbols between every letter.
Example
User types in the word Python.
The word will be shown as =P=y=t=h=o=n= or -P-y-t-h-o-n- or maybe with * between every letter.
Is this an easy task? Can someone help me how to go about doing this?
Thank you.
Joel
If you want to do it yourself, you can go through your string like this:
my_string = "Python"
for letter in my_string:
# do something with the letter
print(letter)
This will print each letter in your word. What you want to do is having a new string with your desired character. You probably know you can concatenate (append) two strings in this way :
str1 = "hello"
str2 = "world"
str3 = str1 + str2
print(str3) #helloworld
So to do what you'd like to do, you can see each letter as a substring of your main string, and your desired character (for example *) as another string, and build a result string in that way.
inputString = "Python"
result = ""
myChar = "*"
for letter in inputString:
# build your result
build = build + letter
print(build)
This will just copy inputString into result, though I think you'll have understood how to use it in order to add your custom chars between the letters.
Yes python makes this sort of string manipulation very easy (some other languages... not so much). Look up the standard join function in the python docs.
def fancy_print(s, join_char='-'):
# split string into a list of characters
letters = list(s)
# create joined string
output = join_char + join_char.join(letters) + join_char
# show it
print(output)
then
>>> fancy_print("PYTHON")
-P-Y-T-H-O-N-
>>> fancy_print("PYTHON", "*")
*P*Y*T*H*O*N*

Categories