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)
Related
More information
Below is my code. I am in the process of making a small program that finds Palindromes. I want the program to take user input, save it to a variable, and then check for any spaces. If it finds a space to save its index, and then to take it out to check for a Palindromes. Out of curiosity and to further my programming skills, I want to be able to add the space back later while the word is in reverse. For example, nurses run = nursesrun backward and forwards, but I also want to display it backward and add the space back.
word = input("Please enter a word")
storeVal = word.count(" ")
print()
newWord = word.replace(" ", "")
print(newWord)
print()
while True:
if newWord == "":
print("Sorry, but you did not enter a word")
break
elif newWord == newWord[::-1]:
#use the index storeVal and add it in the string to put a space back
print(" is a palidrone")
break
elif newWord != newWord[::-1]:
print("This is not a palidron")
break
else:
print("You have reached an error")
Also, if you have any suggestions for how I can improve my ability to ask this question or a better way I can write this question, please let me know. Thank you for reading.
Just reverse word instead of reconstructing the modified newWord!
print("{} is a palidrone".format(word[::-1]))
Also storeVal in your example isn't storing the index of the space -- it's storing the number of spaces in your input string.
As per the other answer, just for displaying you can print word instead of newWord. But if you want to learn how get the original positions of spaces, here are a few hints:
word.find(" ") will give you the index of the first space or -1 if none found, you can save it into a list, and than call word.find(" ", space_index + 1) to call the next one, where space_index is the index of last found space, until you get -1 which means no more spaces
another, more educated (to my opinion), would to enumerate the string and collect all indexes for spaces in a list using list comprehension (or set, of you don't care about the order).
I am trying to check the input to see if it has any extension here is the code I used:
filename=input()
if "." in filename:
print ("There is")
However this will return "there is" even if the input is ends with just a full stop.
Is there any way to check if the input has any letters after the "."?
I can't specify what the extension should be (as it is up to the user), just that there should be an extension.
An easy option would be to check for "." in filename with the last character removed:
if len(filename)>1 and "." in filename[:-1]:
print("there is")
This would allow "file..", which may or may not be what you want. Another idea would be, to split filename at every "." and check that you get at least two parts, the last of which is non-empty:
parts = filename.split(".")
if len(parts) > 1 and parts[-1]:
print("there is")
This will not allow "file..", but will allow "file.,". If you want to only allow extensions which consist of letters, you should probably use regular expressions. For example, you could try the following:
import re
m = re.match('[a-z]*\.[a-z]+', filename)
if m:
print("there is")
This will allow "file.txt", but not "a.b.c". Regular expressions are very flexible and this approach can be extended to check for quite specific name formats.
I used the find function to locate the character . in me. If the character doesn't exist in me, the function returns -1. Then, with the index of the . character, I see if there are any characters after that index with len(me[index + 1:]). If the len function returns a positive number, then you know there are characters after the . character.
me=input()
index = me.find(".")
if (index != -1 and len(me[index + 1:]) > 0):
print ("There is")
It might not be the most elegant way to solve this with Python, but it covers the basics of your problem without getting too fancy.
Split the string on the dot and check to see if there was anything after it.
s = 'aaa.'
if s.strip().split('.')[-1]:
print('extension')
else:
print('no extension')
s = 'aaa.bbb'
if s.strip().split('.')[-1]:
print('extension')
else:
print('no extension')
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 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.
I'm trying to write a program that asks the user for a string input without using global variables. If the string has parentheses only side by side, then it's even. if it has letters, numbers, or the parentheses are spaced out, then it's uneven. For example, () and ()() is even, whereas (() and (pie) is not. Below is what I've written so far. Do I have to create more than one function for this problem?
def recursion():
string = str(input("Enter your string: "))
if string == "(" or ")":
print("The string is even.")
else:
print("The string is not even.")
A really useful stdlib script shlex provides this type of parsing automatically and allows you to customize the behavior.
No, you do not need to make multiple functions for this. In fact, I would personally just do this:
def recursion():
print("The string is not even." if input("Enter your string: ").replace('()','') else "The string is even.")
There really isn't a need to have a 6 line function for this job. Instead, use a ternary statement like I did to keep it concise.
Also, just wanted to mention this, there is no need to do:
str(input())
because input always returns a string in Python 3.x.
I will collect much of the information in the comments into an answer.
First, in your posted code the line
if string == "(" or ")":
will always evaluate to True because a non-empty string is always True. What you have written is equivalent to:
if ( string == "(" ) or ")":
which is therefore equivalent to
if ( string == "(" ) or True:
which is always True.
Next, since it seems that you simply want to check if your string consists only of sets of '()', you can use Jon Clements' suggestion of not string.replace('()',''):
if not string.replace('()', ''):
Let's take a look at what this does:
>>> not '()'.replace('()', '')
True
>>> not '()()'.replace('()', '')
True
>>> not '(()'.replace('()', '')
False
>>> not '(pie)'.replace('()', '')
False
Last, you shouldn't call a variable string because it shadows a module in the standard library. Something like user_given_string might work.
Summing it all up:
def recursion():
user_given_string = input("Enter your string: ")
if not user_given_string.replace('()', ''):
print("The string is even.")
else:
print("The string is not even.")