Comparing two string in python - python

Is there any in build function in python which enables two compare two string.
i tried comparing two strings using == operator but not working.
try:
if company=="GfSE-Zertifizierungen":
y=2
if x<y:
print "**************Same company***********"
x=x+1
flag=0
pass
if x==y:
flag=1
x=0
count=count+1
except Exception as e:
print e
This is not even showing any error nor working out.
Can anyone assist me where I m going wrong

In python to compare a string you should use the == operator.
eg:
a = "hello"
b = "hello2"
c = "hello"
then
a == b # should return False
a == c # should return True
Suggestion: print the content of your variable "company" to check what's inside of it. Be sure to have the same case (lower/upper letters).

The == operator for strings in python compares each letter of one string to another. If they are all the same, the string is equal.
The only two possibilities here are that you are not reaching the line
if company=="GfSE-Zertifizierungen":
or company is not actually the same.
To help troubleshoot, add something like:
try:
print "Got to here"
print company
if company=="GfSE-Zertifizierungen":
y=2
....

You can use == to check both the string are equal or not.
The problem is not with your if statement.
>>> company="GfSE-Zertifizierungen"
>>> if company == "GfSE-Zertifizierungen":
print "OK"
else:
print "NOT OK"
Output:
OK
You can use debugger to see whats wrong with your code.

Related

Words in a string return unexpected value

Why does my boolean return True when I expect False?
String a is "7582 + group by 1,2; ERROR: File ACT2EST.SUMMARY_CFS.DATA does not exist."
My code expression is "WARNING" and "ERROR" in a; this evaluates to True.
I apply the same code, "WARNING" and "ERROR" in b, to another string b = "if abc ; WARNING: message. ERROR Message.", and my output is True as expected.
Can someone let me know what is wrong with my code and why when running it with string a my output is True instead of False? Btw, I use python 2.7
Yes, because you did not check to see whether "WARNING" is in the string; all you checked was the truth value of the string. You need
"WARNING" in a and "ERROR" in a
Logical operators do not distribute over their objects the way they can in English.
If you want to get fancy, you could do:
a = "This is a demo text"
if any( x in a for x in ["This", "rocks", "scissors"] ):
print("Text contains any of This, rocks, scissors")
else:
print("Text has neither of This, rocks, scissors")
if all( x in a for x in ["This", "rocks", "scissors"] ):
print("Text contains all of This, rocks, scissors")
else:
print("Not all in!")
any and all are built-ins:
https://docs.python.org/3.2/library/functions.html#any
https://docs.python.org/3.2/library/functions.html#all
that operate on iterables and check if any/all in the iterable are True
For only 2 values simply chaining if "this" in a and "that" in a: is ok though

how to check if string is palindrome of another string

I am trying to check if a string that is passed in to a function is a palindrome of the second string that is passed in. Google defines a palindrome to be a word that is the same spelled forwards or backwards.
def palindrome(strA, strB):
if (strA == strB and strA[::1] == strB):
print "true"
else:
print "false"
if __name__ == '__main__':
palindrome("sirap", "paris")
In the code above, I am attempting to check if the given string is equal to the second string both forwards and backwards yet the test i give it in main returns false. Any ideas on what im missing?
You check if 'sirap' is the same as 'paris' as well as checking if reversed 'sirap' is the same as 'paris'. You just have too many things in your if:
if strA[::-1] == strB:
print "true"
else:
print "false"
What you had would work if you passed in a palindrome as well as its reverse, the same thing. For example, palindrome("stats", "stats") would print "true", but I don't think that's what you had in mind. You will also notice that I used strA[::-1] instead of strA[::1]. That is because strA[::1] starts at the beginning and goes to the end, but you want to go backwards, so you should use -1.
You could even do it in one line:
print ("false", "true")[str[::-1] == strB]
I did a similar test using the "100 projects" to learn python (useful for learning any language)
You could do something like this, and just run the script. For this I just made some changes to the original palindrome script I wrote.
print "This will check if its a palindrome"
inputstring = raw_input("String1: ")
inputstring2 = raw_input("String2: ")
inputstring = inputstring.lower()
inputstring2 = inputstring.lower()
revstring = inputstring[::-1] #Reverses the string
if revstring == inputstring2:
print "Yes: " + revstring
else:
print "No: " + revstring

Why won't my True statement work?

Here is a dictionary:
Vocab ={'Adherent' : " supporter; follower.",
'Incoherent' : "without logical or meaningful connection; disjointed; rambling",
'Inherent' : "existing in someone or something as a permanent and inseparable element, quality, or attribute"}
I've created a simple set of if statements in a loop:
while 1:
x = Vocab[random.choice(Vocab.keys())]
print x
t1=raw_input("What word matches this definition?: ")
if t1 in Vocab == True:
if Vocab[t1] == x:
print "That's correct!"
elif Vocab[t1] != x:
print "That's wrong!"
else:
print "That's not a word!"
raw_input("Hit 'enter': ")
For some strange reason, when the user inputs a key that is in the dictionary, the code outputs:
"That's not a word"
Why isn't the if statement with the '== True' working?
You don't need to use if t1 in Vocab == True, simply use if t1 in Vocab.
The problem is the operand precedence. The == has priority over in, so when you write if t1 in Vocab == True python interprets as if t1 in (Vocab == True).
To fix the precedence issue, you can write like this: if (t1 in Vocab) == True:, but again there is no need to compare if the result of t1 in Vocab is True, simple use this:
if t1 in Vocab:
You shouldn't need to use the "== True." Python should evaluate the if statement when you use this syntax without that.
A couple of things. First, if you're on Windows, there is the possibility that it might not be stripping the '\r' at the end of the input line, or you might have extra whitespace in general from your input. But also, you can simplify your code significantly, as so:
t1=raw_input("What word matches this definition?: ")
try:
if Vocab[t1.strip()] == x: # This should fix your 'not a word' problem
print "That's Correct"!
else:
print "That's Wrong!"!
except KeyError:
print "That's not a word!"
There's no need to test if a key is in a dictionary before using it. Simply try and use it and then catch the resulting KeyError.
edit
#MagnunLeno is also totally correct about the precedence problem, although simplifying your code as I have recommended makes it a moot point.

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

How to check whether a str(variable) is empty or not?

How do I make a:
if str(variable) == [contains text]:
condition?
(or something, because I am pretty sure that what I just wrote is completely wrong)
I am sort of trying to check if a random.choice from my list is ["",] (blank) or contains ["text",].
You could just compare your string to the empty string:
if variable != "":
etc.
But you can abbreviate that as follows:
if variable:
etc.
Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.
The "Pythonic" way to check if a string is empty is:
import random
variable = random.choice(l)
if variable:
# got a non-empty string
else:
# got an empty string
Just say if s or if not s. As in
s = ''
if not s:
print 'not', s
So in your specific example, if I understand it correctly...
>>> import random
>>> l = ['', 'foo', '', 'bar']
>>> def default_str(l):
... s = random.choice(l)
... if not s:
... print 'default'
... else:
... print s
...
>>> default_str(l)
default
>>> default_str(l)
default
>>> default_str(l)
bar
>>> default_str(l)
default
Empty strings are False by default:
>>> if not "":
... print("empty")
...
empty
For python 3, you can use bool()
>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True
Some time we have more spaces in between quotes, then use this approach
a = " "
>>> bool(a)
True
>>> bool(a.strip())
False
if not a.strip():
print("String is empty")
else:
print("String is not empty")
element = random.choice(myList)
if element:
# element contains text
else:
# element is empty ''
How do i make an: if str(variable) == [contains text]: condition?
Perhaps the most direct way is:
if str(variable) != '':
# ...
Note that the if not ... solutions test the opposite condition.
if the variable contains text then:
len(variable) != 0
of it does not
len(variable) == 0
use "not" in if-else
x = input()
if not x:
print("Value is not entered")
else:
print("Value is entered")
{
test_str1 = ""
test_str2 = " "
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(len(test_str1) == 0):
print ("Yes")
else :
print ("No")
# prints No
print ("The zero length string with just spaces is empty ? : ", end = "")
if(len(test_str2) == 0):
print ("Yes")
else :
print ("No")
}
string = "TEST"
try:
if str(string):
print "good string"
except NameError:
print "bad string"
Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size.
Let’s see two different methods of checking if string is empty or not:
Method #1 : Using Len()
Using Len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as an empty string even its non-zero.
Method #2 : Using not
Not operator can also perform the task similar to Len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.
Good Luck!
#empty variable
myvar = ""
#check if variable is empty
if not myvar:
print("variable is empty") # variable is empty

Categories