i tried to compare 2 string in python but it fails - python

so I wnt to compare a string in a iist and variable but the output is awlays false
ive used is and == then I thought because elemen in my list is not string then I try to chnage it in to a str using str() func but it doesnt work
obj='ana'
# haha[22][0] is 'ana'
obj1=str(haha[22][0])
if obj is obj1:
print('true')
else:
print('false')
print(obj1)
first I tried to change == into is but it doesnt work then I though I need to change elemen in my list into str() it doenst work too
I would like to compare it thank you so much for the answer

This is almost certainly something to do with what's stored in your list. Also in general == is for comparing value and 'is' is for comparing identity so you should use == in this situation.
What is output by the last print?
'ana' == 'ana' will always return true so without specifying where the element is set there isn't enough information to work out what your issue is.
If it prints 'ana' it may be worth printing the hash function of each object to compare.
I'd like to have written this as a comment but I don't have enough rep to comment :/

Related

How to make a bool return true/false using the return function inside def in Python?

I was given a task to make a code which takes a word, checks if there are any vowels in it, then returns true if there are vowels inside the word, and false if no vowels are there inside the given word. This is what I wrote-
def search4vowels(word):
vowels = set('aeiou')
found = vowels.intersection(set(word))
return(bool(found))
search4vowels('test')
Here, I was expecting found to contain either none (Or 0 vowels) or the value of the vowels. Then use the return function with bool
to get true or false depending on the value of the variable found However, when I ran the code, nothing was printed. I also changed the last line under def return(bool(found)) to return bool(found) but that did not print anything either. This might be a really dumb/stupid question but I am really a beginner and actually don't know why nothing is getting printed despite the use of the return function. I checked on various websites also but did not understand why this was happening. Thanking you in advance, Have a great day ahead!
Try adding a print statement to show the output:
print('Result:', search4vowels('test'))

Trouble with Palindrome function in python

I'm having trouble in an online course for python, specifically a palindrome problem These are the instructions, but the function must be case-insensitive and not see spaces. I think the issue is in my return blocks or my flow. I think I need to use the lower function, but I'm honestly not sure.
def student_func(x):
for string in x:
x.lower()
y = x.replace(" ", "")
if y[::-1]==y:
return True
else:
return False
You actually have two separate problems in your code—and you're right that one of them is with lower and the other is with the return flow.
First, x.lower() doesn't modify x in-place. In fact, strings are immutable; nothing modifies them in-place. If you look up the interactive help or the online docs, it says:
Return a copy of the string with all the cased characters [4] converted to lowercase.
So, you need to do the same thing with lower that you do with replace: assign the result to a variable, and use that:
y = x.lower()
z = y.replace(" ", "")
Or you can reuse the same variable:
x = x.lower()
… or chain the two calls together:
y = x.lower().replace(" ", "")
As a side note, unless you're using Python 2, you should consider whether you want casefold instead of lower. For English it makes no difference, but for other languages it can.
Meanwhile, you're doing for string in x:, but then ignoring string.
If x is just a single word, you don't want to loop over it at all.
If x is a list of words, then the for string in x: is correct, but then you have to use string inside the loop, not x. Plus, you can't just return True or return False—that will exit the function as soon as you test the first word, meaning the rest of them never get tested. I'm not sure whether you want to return True if there are any pallidromes, or if they're all palindromes, or if you want to return a list of booleans instead of a single one, or what, but you can't just return the first one.
It would probably be a lot clearer if you used better names, like words instead of x and word instead of string.
Anyway, I can't tell you the right way to fix this since I don't know what you're trying to do, but hopefully this explains enough that you can fix it yourself.
Giving away the solution defeats the purpose of the exercise
your approach is more or less correct.
convert string to a standard case
remove whitespace
check if reverse of the string is equal to the original string
The error lies in how you are using the python API.
check what each of the functions do, and what they return.
a good idea is to run help(function) to see what the function's documentation has to say about it.
try help(x.lower) (note: not help(x.lower())) and see what the return value is.

str.upper() returns a string which apparently does not equal anything, including another str.upper() [duplicate]

This question already has answers here:
Why does comparing strings using either '==' or 'is' sometimes produce a different result?
(15 answers)
Closed 6 years ago.
I've been trying to use Python's one function dedicated to making every letter in a string uppercase, but after using it on a string booleans don't work on that string. What do I mean you ask? Well let's just say the following booleans:
"b".upper() is "B"
".".upper() is "."
".".upper() is ".".upper()
are all false.
I'm so confused. It acts like after I convert a string to upper() form, instead of returning the same string with uppercase letters (which is what the documentation says it does), it returns a whole new object that doesn't equal anything even an object produced in the exact same conditions.
Setting breakpoints and looking at the actual values of the variables seems fruitless. I hover over is_graduate_input = input("Enter (y/n)").upper()
and it shows me a value of "Y", because that's what I entered. But then directly after that line my print(is_graduate_input is "Y") statement prints out False?!?! Why?!?!
The documentation for python says that their algorithm for making letters uppercase is described in some Unicode standard. I don't want to read through it. I don't think it will help. Can someone just please tell me what the hell is going on. I want to go to bed. I have school tomorrow.
is will return True if two variables point to the same object id
== will return True if the objects referred to by the variables are equal.
What you are doing is comparing two different objects here and hence getting False.
"b".upper() is "B" # will return False
What will work for you is
"b".upper() == "B" # will return True
Say you start with
a = "b"
b = "B"
print(id(a))
print(id(a)) # will print same id as above.
print(id(b))
print(id(b)) # will print same id as above.
output:
4337047792
4337047792
4337610568
4337610568
But if you print id for a.upper() it will return a new object each time and print a new id.
print(id(a.upper()))
print(id(a.upper()))
output:
4372772488
4372772376
This is the reason why "b".upper() is "B" # will return False. Because the id wont match.
you can read up more on these threads:
why does comparing strings in python using either or is sometimes produce
understanding pythons is operator

is operator python in file

Just encountering this problem, it baffles me! My code just wants to compare song[-3:] is "mp3" which would, if I didn't use is, pass, but through all the patience I have with things out of my comprehension, I've found a peculiar behavior. I learned that is supposedly tests to see if two things are the same instance or whatever, but when the value IS the same, why, oh why, does it fail? When I test the id of two strings on one line, another line, using the is operator, then the == operator:
>>> id("String"[-3:]), id("String"[-3:])
(4347723880, 4347723880)
>>> id("String"[-3:])
4347241952
>>> "String"[-3:] is "String"[-3:]
False
>>> "String"[-3:] == "String"[-3:]
True
so I suppose my question is, why does the id change when when I use is, or when tested on a separate line, but not when on the same line? Is this some strange exception, or is this some oversight on my part?
is tests if they are the same string, not just identical strings. Since strings are immutable, Python can choose to reuse old strings if you ask for one with the same value - you are encountering some situations where it does choose to do this. As you've seen, it doesn't always. The rules for when it does aren't guaranteed. To get the right result in all circumstances, use str1 == str2 whenever you mean "do these strings have all the same letters".
It happens because when you do:
"String"[-3:] is "String"[-3:]
python creates two different objects with different id.
When you call "String"[-3:], python gives you a string object. And if there is a same str. Two str should be the same. But if you dont assign "String"[-3:] to a varible.The "String"[-3:] will be "disapeared". I tested if you use a="String"[-3:]. then the id of "String"[-3:] wouln't change anymore

"is" not working in python IDE but working in command line

I couldn't understand why this is happening actually..
Take a look at this python code :
word = raw_input("Enter Word")
length = len(word)
if word[length-1:] is "e" :
print word + "d"
If I give input "love", its output must be "loved". So, when I wrote this in PyScripter IDE, its neither showing error nor the output. But I tried the same code in python shell, its working!
I'd like to know why this is happening.
The is keyword will only work if the strings have exactly the same identity, which is not guaranteed even if the strings have the same value. You should use == instead of is here to compare the values of the strings.
Or better still, use endswith:
if word.endswith("e"):
print word + "d"
You should use == in this case instead of is. Is checks for identity of objects, that is, id('e') would have to be equal with id of the string returned by the slice. As it happens, cpython stores one-letter strings (and small integers) as constants so this often works. But it is not reliable as any other implementation could not use this and then even "e" is "e" wouldn't have to yield True. Just use == and it should work.
edit: endswith mentioned by #MarkByers is even better for this case. safer, more readable and all that

Categories

Resources