isalpha python function won't consider spaces - python

So the code below takes an input and makes sure the input consists of letters and not numbers. How would i make it also print orginal if the input contains a space
original = raw_input("Type the name of the application: ")
if original.isalpha() and len(original) > 0:
print original
else:
print "empty"
tried this code but worked when the input was a number too.
original = raw_input("Type the word you want to change: ")
if original.isalpha() or len(original) > 0:
print original
else:
print "empty"

It looks like that's just how string works.
Two options:
if all(x.isalpha() or x.isspace() for x in original):
(modified on inspectorG4dget's recommendation below)
or
original.replace(' ','').isalpha()
should work.

Related

How to check if list of strings entered are in alphabetical order?

I have a program which takes a series of strings from user input and should print "Yes" if the strings entered are in alphabetical order and "No" if not. The program ends by the user entering an empty input. I can do this when I specify the number of inputs it should have, eg 2:
finished = False
while not finished:
print("Please enter a string: ")
s = input()
x = input()
if len(s) != 0:
if s < x:
print("Yes")
else:
print("No")
else:
finished = True
However I can't seem to get my code to work when there is an indefinite amount of strings that can be entered. My current working method is to append all the strings to a list and perform the checks there, but I'm not sure exactly how to write the if statement to check this:
lst = []
i = range(len(lst))
finished = False
while not finished:
print("Please enter a string: ")
s = input()
lst.append(s)
if len(s) != 0:
if lst[i:] < lst[i: - 1]:
print("Yes")
else:
print("No")
else:
finished = True
Is there an easy way to achieve this without deviating too far from the intended structure above?
lst is a list of strings, slicing syntax on that will get you a list of strings back. But you want a string instead. Since you're appending to the list, the latest string appended will be present in the [-1] index, and the previous one will be present in [-2] index.
Change lst[i:] < lst[i: - 1] to lst[-2] < lst[-1]
There's still another problem though, in the first iteration lst[-2] does not exist, because there is only one string that has been inputted, to get rid of this - take one input and append it to the list before the loop starts-
print("Please enter a string: ")
s = input()
lst.append(s)
finished = False
while not finished:
# rest of your code
You can use the following to always compare the new item to the last item in the existing list. Therefore it always checks, if the next item is in order
new_input = input()
existing_list = ...
if sorted(existing_list[-1], new_input)[-1] == new_input
existing_list.append(new_input)
print("Yes")
else:
print("No")
That way, you don't have to enter the value to the list before checking
I have made some changes to your code. There is no need for two inputs and a master list. The code is as below.
Assumptions
Assumes that items in the list are separated by a single space
The difference between a capital case character and small case character is not important. If this is not true and ASCII ordering is important then remove ".lower()" from the third line.
while True:
print("Please enter a string: ")
s = input().lower() ## To avoid confusion between sorting ABb Abb and like strings
if not s: ## If nothing is entered break out of loop
break
SplitString = s.split(" ") ##Get elements separated by "single" space into list
SortedString = " ".join(sorted(SplitString)) ##Sort the list and then join into string
if s == SortedString: ##If the sorted and joined string is same as original then the string was already sorted when entered
print("Yes")
else: ## Else it was not sorted when entered
print("No")
The output is as below
Please enter a string:
AAA AAB ABA ABC
Yes
Please enter a string:
AAA AAB ABC ABA
No
Please enter a string:
aaa aab aba abc
Yes
Please enter a string:
aaa aab abc aba
No
Please enter a string:

how to store all iterations of a for loop in python

So here is what I have. This is a program in which I have to take a random string, ex) "]][][sfgfbd[pdsbs]\bdgb"; and strip it of all special characters. the function "Strip" works for its purpose.
message=(str.lower(input("Enter a Coded message: ")))
offset=int(input("Enter Offset: "))
alphabet="abcdefghijklmnopqrstuvwxyz"
def strip(text):
print("Your Lower case string is: ",message)
print("With the specials stripped: ")
for index in text:
if index in alphabet:
print(index, end="")
print()
return strip
I need the output from strip in the "decode" function, but I can't seem to figure out anyway of storing the iterations of "index"
def decode(character):
encrypted= ""
for character in message:
global offset
if character == " ":
encrypted+= " "
elif ord(character) + offset > ord("z"):
encrypted+=chr(ord(character) +offset - 26)
else:
encrypted+= chr(ord(character)+(offset))
print("the decoded string is: ",encrypted,end=" ")
print()
So "decode" only takes the output from the original "message" input. "Palin" however succeeds in taking decode's value.
def palin(code):
print(code[::-1])
print(code[:])
if code[::-1]==code[:]:
print("This is a Palindrome!")
else:
print("This is not a Palindrome.")
return palin
print()
palin(decode(strip(message)))
Don't get confused between print and return.
You need to look carefully at the outputs of your methods (what they return, not what they print to the console):
the strip() and palin() methods are returning references to themselves, rather than anything useful relating to their inputs.
the decode() method isn't returning anything.
To fix this, you can use a variable inside your method, that you build based on the input variables, using the logic you want. For example:
def strip(text):
print("Your Lower case string is: ",text)
print("With the specials stripped: ")
stripped_text = "" # <-- create and initialise a return variable
for index in text:
if index in alphabet:
stripped_text += index # <-- update your return variable
print(index, end="")
print()
return stripped_text # <-- return the updated variable
You then need to do something similar for decode(), although here you already have an output variable (encrypted) so you just need to return it at the end of the method.
The palin() method doesn't need to return anything: it just prints out the result.
Once you get this working, you should think about how you can use other features of the Python language to achieve your goals more easily.
For example, you can use replace() to simplify your strip() method:
def strip(text):
return text.replace('[^a-z ]','') # <-- that's all you need :)

White space counter

Your program should ask the user to input the list, then it should call the function, and print the result. with the following condition:
It returns True if the given list has at least 2 white spaces and False otherwise.
My code:
n = ((input("Please input a list of numbers separated by space:")))
t = 0
k = n.count(' ')
for i in range(0,len(n)):
if n[i] > " ":
print("True")
else:
print("False")
print("There are",k,"space which has two length run")
My program counts all of the white spaces, but I want it to only count the 2 white spaces or more and return True or False otherwise
I see several issues with this code.
First, you do not define a function as stated in the requirements.
Second, k = n.count(' ') already counts all the spaces in the input string. You do not need to loop over each character.
Third, even if you did need to loop over the characters, n[i] > " " is definitely not the right way to do what you want.
Fourth, what is the purpose of the t variable?
Fifth, why is input() enclosed in two extra layers of parentheses?
Not clear why you think you need a loop.
Try simply
print(n.count(' ') >= 2)
Or rather
def foo(n):
return n.count(' ') >= 2
print(foo(input("Enter some numbers:")))

Counting arguments in lists and printing lists

I want users to enter random words/numbers/phrases. If they have entered more then 5 then they get an error message and if the enter 5 or less then I print out the list vertically. I don't know what code to use so that it does not count the white spaces. As well, I want to count the number of words/numbers, NOT the amount of characters. If you could just take a look at my code and give some help, that would be great!
myList = []
myList = raw_input("Enter words,numbers or a phrase (a phrase should be entered between two quotations)...")
if len(myList) > 5:
print('Error')
else:
#print output
for variable in L:
print variable
Try something like this using str.split() to return a list of the words in the string using the default delimiter of a space character:
myList = []
while(True):
myList = raw_input("Please enter words or numbers: ")
if(len(myList.split())) <= 5:
break
else:
print("Error: You entered more than 5 arguments, Try again...")
for item in myList.split():
print(item)
Try it here!
The working code for what you want is the following:
# I separate the input text by the spaces
data = raw_input("Enter something... ").split(" ")
# handle the data
if len(data) > 5:
print("Only 4 or less arguments allowed!")
else:
for variable in data:
print(variable)
Now, this doesn't prevent the user from inserting other characters like !, $%"#$, so to handle that case, you should check for some of the answers in this question: Stripping everything but alphanumeric chars from a string in Python
Have fun!

python help! If/else statement

I have been learning python through code academy. It asked me to create a if else statement that prints the users input, but if there is no input print "empty". I did pass the tutorial but when there is a user input it prints both the users input and "empty".
here is my code:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len("original")
if length > 0:
print original
else: length < 0
print "empty"
Notice that print under else is not indented. I thought you had to indented it, but when i do it gives me an error.
You seem to have a couple issues with your code. First I believe you should change your assignment of length to:
length = len(original)
That way you get the correct length of the string you binded to the name original. If you use len("original"), you will pass the string "original" to the len() function, and it will just count the characters in that string. Regardless of what the user of your program inputted, your length will always be 8, since that's how many characters are in the string "original"
Also keep in mind that the len() function will never return a negative value. So testing if length < 0 doesn't make sense. You probably wanted to test if it equals 0. It seems as if you were trying to use an elif statement.
Try:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
elif length == 0:
print "empty"
elif statements let you test conditions just like if statements. elif is short for "else if".
Furthermore, as #chepner pointed out in the comments, there is no need to even test the second condition at all. You can just as easily go with:
else:
print "empty"
The else syntax is not followed by any condition. It automatically enters the indented block of code if the other conditions evaluate to False.
Was the length < 0 intended to be a comment? You need the comment character #.
else: # length < 0
print "empty"
It's wrong anyway, it should be length <= 0.
Without a comment character it was being interpreted as the statement to use as the else clause. It didn't create an error since length < 0 just generates a boolean result that you didn't do anything with, but it prevented you from having another statement as part of the else.
else: length < 0
print "empty"
should be
elif length == 0:
print "empty"
Python has significant whitespace, things that are indented the same are in the same scope.
First off, it is not len("original") it is len(original). If you use quotes you are making it a constant value, "original", rather than a variable named original.
Second, instead of checking the length of the string you should use this
if original:
# Type here what happens if the string is not empty
else:
# Here what happens if the string is empty
By Python standard any collection, including strings, equals false if it is empty(aka contains no elements) and true if it contains any elements.
There is a a statement after else.
else: length < 0
print "empty"
Maybe you are looking for an (elif is another way to check another condition after the if if the previous if fails.)
elif length <= 0:
or just a plain
else:
print "empty"
it will never go past zero anyways you could have a == conditional for zero and it would work.
elif length == 0:
this is probably the best way there is no need to check another condition.
if length > 0:
print original
else:
print "empty"
also just a side note length = len("original")
there is not suppose to be quotation marks around original because its a variable :). You will just be getting the string "original" not the actual stuff inside of the variable.
The end result ..
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
else:
print "empty"
To check if there is an item in a list, simply do this:
if List_name:
{code here}
...
So, your code should very simply look like this:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
if original:
print original
else:
print "Empty"
It's that easy :D

Categories