I'm writing a program that checks if a word or sentence given by user input is a palindrome or not. This is the program so far:
def reverse(text):
a = text[::-1]
if a == text:
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
string = str(raw_input("Enter word here:")).lower()
reverse(string)
However, this code doesn't work for sentences. So I tried to do it like this:
import string
def reverse(text):
a = text[::-1]
if a == text:
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
notstring = str(raw_input("Enter word here:")).lower()
liststring = list(notstring)
forbiddencharacters = string.punctuation + string.whitespace
listcharacters = list(forbiddencharacters)
newlist = liststring - listcharacters
finalstring = "".join(newlist)
reverse(finalstring)
My goal is to put the punctuation and whitespace into a list and then subtracting those characters to the input of the user so that the program can tell if it's a palindrome even if the string has punctuation and/or whitespace. However, I don't know how I can subtract the elements in a list to the elements in another list. The way I did it, by creating another list that equals the user input minus the characters doesn't work (I tried it in my Xubuntu terminal emulator). Apart from that, when I run the program this error appears:
Traceback (most recent call last):
File "reverse.py", line 12, in <module>
forbiddencharacters = string.punctuation + string.whitespace
AttributeError: 'str' object has no attribute 'punctuation'
Ok so I have changed the variable name and I don't get that mistake above. Now I still don't know how to subtract the elements of the lists.
Since I'm a beginner programmer this might seem stupid to you. If that's the case, I'm sorry in advance. If anyone can solve one or both of the two problems I have, I'd be extremely grateful. Thanks in advance for your help. Sorry for bad english and long post :)
You should add some filtering along the way since palindromes have various syntax tricks (spaces, commas, etc.).
palindrome = "Rail at a liar"
def is_palindrome(text):
text = text.lower() #Avoid case issues
text = ''.join(ch for ch in text if ch.isalnum()) #Strips down everything but alphanumeric characters
return text == text[::-1]
if is_palindrome(palindrome):
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
You are on the right track, but you have used the identifier string for two different purposes.
Since you assigned to this variable name with the line:
string = str(raw_input("Enter word here:")).lower()
You can now no longer access the attributes string.punctuation and string.whitespace from the import string, because the name string is no longer bound to the module but to the user input instead.
A somewhat different approach to testing if a string is a palindrome
def palindrome(s):
s = s.lower()
ln=len(s)
for n in xrange(ln/2):
if s[n] != s[(ln-n)-1]:
return False
return True
print palindrome('Able was I ere I saw Elba')
FYI -- you'll need to tweak this to strip punctuation and white space if you like (left an an exercise to OP)
You can do that by splitting the phrase and storing it in a list. I am going to use your function (but there are more better pythonic ways to do that).
def reverse(textList1):
textList2 = textList1[::-1] #or we can use reversed(textList1)
if textList2 == text:
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
test1= "I am am I"
You should split the phrase and store it in a list:
test1List= test1.split(' ')
reverse(test1List)
Checking for palindrome is simple,
This works for both words and sentences.
import string
def ispalindrome(input_str):
input_str = list(input_str)
forbidden = list(string.punctuation + string.whitespace)
for forbidden_char in forbidden: # Remove all forbidden characters
while forbidden_char in input_str:
input_str.remove(forbidden_char)
return input_str == list(reversed(input_str)) # Checks if it is a palindrome
input_str = raw_input().lower() # Avoid case issues
print ispalindrome(input_str) # Get input
Related
def censor(text,word):
t=str(text)
w=str(word)
if w in t:
l=len(w)
item = ("*" * l)
return t.replace(w,item)
else:
return t
print(censor("salad","s"))
So instead of having two parameters, I would want a variable that asks the user for a sentence and then it checks if there are any curse words, if there isn't, it returns it unchanged
It's a good idea to keep a useful function like 'censoring a text' in a function and user input and output separately, because the function could be easily reused in a situation where you don't want user interaction (like censoring another writting message for example).
It also helps to think ahead a little. Your example finds one word and blots it out, but do you need to censor multiple words? And what if the word is part of another word, is it still a bad word? ("My friend from Scherpenisse, has a massive collection of Dickensian fiction, but ever since they moved to Scunthorpe, they bedamn anything Shakespearean. Hey look, an American bushtit!")
Of course the problem is even harder with names to consider, just ask Dick Cheney and George Bush.
The easy things are quick to fix though:
def censor(text, forbidden):
return ' '.join(
word if word.casefold() not in forbidden else '*' * len(word)
for word in text.split())
print(censor('I like fruit salad\n\nbecause it is fruitilicious', ['fruit', 'produce']))
Why this works:
' '.join(<some iterable>) takes the elements from an iterable like a list and joins them together with the string at the start, a space in this case;
word.casefold() gives you the lowercase, simplified version of a word, to avoid things like aßhole or DaMn slipping through;
x if some_condition else y is an expression with a conditional built in;
'*' * len(word) - just a short version of what you already found.
word for word in text.split() gets you a generator that yield the words in text, split over whitespace, one at a time.
All of it taken together splits up text into words, checks if their simplified (casefolded) version is in the list of forbidden words and replaces them with a mask if so, otherwise, it just leaves the word - and at the end, it combines all of them back together into a sentence.
There are more problems to consider. For example, if you need to preserve the original formatting of a text (perhaps it contains multiple spaces, tabs, etc.) an approach using regular expressions might be better:
import re
def censor(text, forbidden):
for word in forbidden:
text = re.sub(rf'(?:(?<=^)|(?<=\s)){word}(?=$|\s)', '*' * len(word), text)
return text
print(censor('I like fruit salad\n\nbecause it is fruitilicious', ['fruit', 'produce']))
This works mainly because of the regular expression, with these parts:
(?:(?<=^)|(?<=\s)) checks if the string has the start of a line ^ or whitespace \s immediately before it; it's done in two because the Python regex engine requires different options separated by | in a lookbehind to be of the same size;
{word} is replaced in the expression by each forbidden word, for each iteration, thanks to the f at the start of the string;
(?=$|\s) checks that the word is followed by the end of the line, or whitespace.
re.sub(some_regex, replacement, text) finds all occurrences of the given regular expression, and replaces them with replacement, which in this case is a string of the right number of *.
def censor(text, words):
for i in words:
text = text.replace(i, len(i)*'*')
return text
censor("You bloody idiot", ["bloody", "idiot"])
Output:
'You ****** *****'
If you want to ask for user input on the command line in the function itself
you can use input(). You can also just use input() outside of the function and pass that in.
def censor(text, word):
if word in text:
return text.replace(word, "*" * len(word))
else:
return text
sentence = input("Enter your sentence or enter to quit. ")
while sentence:
censored_sentence = censor(sentence, "bad")
print(censored_sentence)
sentence = input("Enter your sentence or enter to quit. ")
using function
def make_cap(sentence):
return sentence.title()
tryining out
make_cap("hello world")
'Hello World'
# it workd but when I have world like "aren't" and 'isn't". how to write function for that
a = "I haven't worked hard"
make_cap(a)
"This Isn'T A Right Thing" # it's wrong I am aware of \ for isn\'t but confused how to include it in function
This should work:
def make_cap(sentence):
return " ".join(word[0].title() + (word[1:] if len(word) > 1 else "") for word in sentence.split(" "))
It manually splits the word by spaces (and not by any other character), and then capitalizes the first letter of each token. It does this by separating that first letter out, capitalizing it, and then concatenating the rest of the word. I used a ternary if statement to avoid an IndexError if the word is only one letter long.
Use .capwords() from the string library.
import string
def make_cap(sentence):
return string.capwords(sentence)
Demo: https://repl.it/repls/BlankMysteriousMenus
I found this method to be very helpful for formatting all different types of texts as titles.
from string import capwords
text = "I can't go to the USA due to budget concerns"
title = ' '.join([capwords(w) if w.islower() else w for w in text.split()])
print(title) # I Can't Go To The USA Due To Budget Concerns
I am using the .isalpha function to take an input of a name. It is working but whenever i put on space between name for example a full name John Doe It gives me error.
What ive Tried so far
while not name.isalpha():
print('Entered Name is invalid')
name = input('Please Enter Your Name Sir: ')
if name.isalpha() or name.isspace():
print('Hello Mr.' + name)
select_mmenu('main-menu.txt')
I've tried combining .isalpha and .isspace but it seems not to be working. Need the most simple way to solve this trick
isalpha tests that each member of the string is a letter. isspace tests that each member of the string is a whitespace character. Neither of those is what you want.
Instead you could do:
if all(lett.isalpha() or lett.isspace() for lett in name):
which will pass if every letter is EITHER a letter or a space. Alternatively you can match a regular expression:
import re # at the top of your module
if re.match(r"[\s\w]+$", name):
which is arguably cleaner, and certainly more powerful. The square brackets denote a character class, \s is all whitespaces and \w is all word character, the + means "matches 1 or more times," and the $ is the end of string. [\s\w]+$ then means "one or more characters that are either whitespace or word characters, and nothing afterwards.
It will certainly give you an error because the method isalpha() checks whether the string consists of alphabetic characters only. So if you put a space, the result will return false instead of true, and you will get an error.
Thankyou for the answers. I got it solved without using all() function. I just solved it with simplest basic Python loops
Thankyou Adam Smith because of your answer i got this idea to solve it through that method
con = False
while con!=True:
l=0
strs = input('Enter your Name: ')
for i in strs:
if i.isalpha() or i.isspace():
l += 1
if l == len(strs):
con = True
break
else:
print('Wrong Input')
if con==True:
print(strs)
In this code its basically counting the input lenght and alphabets and space lenght if it match it works. else the while loop continue.
im trying to code a kind of language translator from any language to a kind of gibberish language, wheres every consonant will be replaced with the same consonant plus an o and then the consonant again.
b = bob
d = dod
f = fof
so the text "Hi my name is x"
will become "Hohi momy nonamome isos xox"
The problem i have is the converting part.
any tips on how i can proceed?
Oh and btw I am using python 3
What i got this far.
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z":
i = i + "0" + i
gibberish.append(i)
elif i == "a,o,u,e,i,y":
gibberish.append(i)
#print out the gibberish
print (gibberish)
Yeah! i think i got it to work quite well..
# -*- coding: cp1252 -*-
#Repeat
while True :
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("Give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i in "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ":
i = i + "o" + i
gibberish = gibberish + i
elif i in "aoueiyåäö AOUEIYÅÄÖ":
gibberish = gibberish + i
#print out the gibberish
print (gibberish)
print ("\n")
Im open for suggestions to make it "better"
The problem is you're comparing a character i to a string "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z". The two will never be equal.
What you want to do instead is use the in operator.
if i in 'bcdfghjklmnpqrstvwxz':
Also, strings don't have an .append() method, only lists do.
You can create a string from a list of strings by doing ''.join(my_list)
If and in statements don't work like that. This is actually a very common mistake, so no worries. When you get to the if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z": python reads that as "if i is all of this string (the string that contains all the consonants). Now unless you enter that string exactly somewhere in your sentence, python is going to think "nope no string like that" and skip it. You have the same problem with your vowel statements.
For the fastest fix:
if i in "bcdfghjklmnpqrstvwxz": #note the removal of commas, don't want them getting "o'd"
#rest of your code for consonants
else: #having an else is often very good practice, or else you may not get a result.
#what to do if its not a consonant
The function checks if it is a lower case vowel (might want to add stuff for upper case letters), then if it isn't, it checks if it is a letter period. string is very useful when working with strings. You should look at the docs.
And finally, you need to change append to just use + with strings.
I was studying Python on this website www.codacademy.com and I'm stuck on exercise PygLatin in part 4 of 12.
"Write an if statement that checks to see if the string is not empty.
If the string is not empty, print the user's word.
Otherwise (else), print "empty" if the string is empty.
Make sure you thoroughly test your code. You'll want to make sure you run it multiple times and test both an empty string and a string with characters. When you are confident that your code works, continue on to the next exercise."
I have to print the user's input word if he does so, if not, print "empty".
original = raw_input("Welcome to the English to Pig Latin translator! Type in the word you wish to use.")
if len(original) > 0:
return raw_input
else:
return "empty"
print original
But it's not working, I need help.
What am I doing wrong? The error claims it's on line 2 (if len(original) > 0:) but I haven't figured out what's wrong.
Wrong indentation is the main problem. Also, you have return statements but don't have a function. Plus, you can simplify the check if original is empty:
original = raw_input("Welcome to the English to Pig Latin translator! Type in the word you wish to use.")
if original:
print original
else:
print "empty"
or, in one line:
print original if original else "empty"
or:
print original or "empty"
You have two main problems: indentation and return without a function.
If you want to use a function, you could define a function that receive a string parameter, checks if it's empty, and then returns the corresponding string.
For example:
def checkstring(string):
if len(string) > 0:
return string
else:
return "empty"
original = "Welcome to the English to Pig Latin translator! Type in the word you wish to use."
print checkstring(original)
You can't indent arbitrarily in Python. The four lines beginning with the if statement are indented one level further than the first statement: that's not allowed. You can only indent after a statement that introduces a new block, as you have done after if and else. Bring those four lines back a level so that they start at the left-hand side.
I got the code from "Quine"but I edited more so you can actually put the input. Works better if you ask me for the purpose of this exercise:
print "Welcome to the English to Pig Latin translator!"
def checkstring(original):
if len(original) > 0:
return original
else:
return "empty"
original = raw_input("What is your name?")
print checkstring(original)
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
raw_input ("What is your name")
variable_name = raw_input ()
original = raw_input()
if len (original) > 0:
print "the user's word"
else:
print "empty"