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
Related
I want to check if a set of numbers is present in a string or not
Here is my code:
def check_no(string):
string = string.lower()
no = set(c)
s = set()
for i in string:
if i in no:
s.add(i)
else:
pass
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
c = input()
print(check_no(c))
if the given set of numbers is present in the string then it prints Valid and if not present it prints Not valid
the program works fine when the input is given as 123 and the string is like I have 12 car and 3 bikes then the output is valid
but when i give input as 254 and string as i hav25555number the output comes as valid but the actual output should be Not valid as 4 is not present in the string.
Can anyone help how to solve it in the provided code
I you want to check if all characters match then use all.
def check_no(text, check):
valid = all(character in text for character in check)
if valid:
return("Valid")
else:
return("Not Valid")
check = '254'
text = 'i hav25555number'
print(check_no(text, check))
The one-liner version
def check_no(text, check):
return 'Valid' if all(character in text for character in check) else 'Not Valid'
Your function is mostly correct, but probably because of your (terrible) choices of variable names, string and c variables were mixed up in the environment.
The solution is to add the parameters explicitly to the function definition (also avoid names like string or c as these could be pre-defined python keywords):
teststring = "254"
testc = "i hav25555number"
def check_no(mystring, myc):
string = mystring.lower()
no = set(c)
print("string is",string)
s = set()
for i in string:
if str(i) in no:
# print(i, " in ", no)
s.add(i)
else:
pass
# print("s is",s)
# print("no is",no)
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
print(check_no(teststring,testc))
gives:
print(check_no(teststring,testc))
string is 254
Not Valid
As mentioned before, you can use all to make your code more elegant, although there is nothing wrong with your implementation either.
How do I stop the index error that occurs whenever I input an empty string?
s = input("Enter a phrase: ")
if s[0] in ["a","e","i","o","u","A","E","I","O","U"]:
print("an", s)
else:
print("a", s)
You can use the str.startswith() method to test if a string starts with a specific character; the method takes either a single string, or a tuple of strings:
if s.lower().startswith(tuple('aeiou')):
The str.startswith() method doesn't care if s is empty:
>>> s = ''
>>> s.startswith('a')
False
By using str.lower() you can save yourself from having to type out all vowels in both lower and upper case; you can just store vowels into a separate variable to reuse the same tuple everywhere you need it:
vowels = tuple('aeiou')
if s.lower().startswith(vowels):
In that case I'd just include the uppercase characters; you only need to type it out once, after all:
vowels = tuple('aeiouAEIOU')
if s.startswith(vowels):
This will check the boolean value of s first, and only if it's True it will try to get the first character. Since a empty string is boolean False it will never go there unless you have at least a one-character string.
if s and s[0] in ["a","e","i","o","u","A","E","I","O","U"]:
print("an", s)
General solution using try/except:
s = input("Enter a phrase: ")
try:
if s[0].lower() in "aeiou":
print("an", s)
else:
print("a", s)
except IndexError:
# stuff you want to do if string is empty
Another approach:
s = ""
while len(s) == 0:
s = input("Enter a phrase: ")
if s[0].lower() in "aeiou":
print("an", s)
else:
print("a", s)
Even shorter:if s[0:][0] in vowels: but of course this not pass as 'pythonic' I guess. What it does: a slice (variable[from:to]) may be empty without causing an error. We just have to make sure that only the first element is returned in case the input is longer than 1 character.
Edit: no, sorry, this will not work if s=''. You have to use 'if s[0:][0:] in vowels:' but this clearly crosses a line now. Ugly.
Just use
if s:
if s[0] in vowels:
as suggested before.
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.
So I recently implemented a code that checks a word to see if it's a palindrome.
def isPalindrome():
string = input('Enter a string: ')
string1 = string[::-1]
if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
print('It is a palindrome')
else:
print('It is not a palindrome')
isPalindrome()
I was wondering if anyone could give me tips on simplifying the code.
Edit - If I were to make the function an iterative function with the statements string == string1, how would I stop the endless while loop? Would I need a count to stop the while loop?
No need for such complex conditional. You already have a reversed string (string[::-1]).
All you need to do is this:
def isPalindrome():
string1 = input('Enter a string: ')
string2 = string1[::-1]
if string1 == string2:
return 'It is a palindrome'
return 'It is not a palindrome'
isPalindrome()
(by the way don't use string as a variable name. That's the name of a built-in module)
It's better to return the strings instead of printing them. That way your function will not return None (preventing some stuff that could happen later)
You can do it in a one liner:
return "Is a palindrome" if string == string[::-1] else "Not a palindrome"
Sample script:
>>> string = "stanleyyelnats"
>>> print "Is a Palindrome" if string == string[::-1] else "Not a palindrome"
>>> Is a Palindrome
You can also do this (although its slower):
print "Is a Palindrome" if string == ''.join(reversed(string)) else "Not a palindrome"
Also, use raw_input and not input. Because input will be evaluated. Let me show you an example:
Script
inp = input("Evaluate ")
print inp
Run
Evaluate "cheese" + "cake"
cheesecake
Here is a simple solution in just 1 LINE.
plandrom = lambda string: True if string == string[::-1] else False
Please check this algorithm,
def is_palindrome(n):
m = len(n)/2
for i in range(m):
j = i + 1
if n[i] != n[-j]:
return False
return True
print is_palindrome('malayayalam')
So, I just got into learning python and I have been trying to these exercises, #8. Though I see that a lot of these answers are creating a new reverse string(which adds a memory overhead) and comparing both strings, I thought I could utilize lesser memory by doing this:
def is_palindrome(s):
l=len(s)
list_s=list(s)
for i in range(0,l):
if(list_s[i] !=list_s[l-i-1]):
return False
else:
return True
You can use a print statement to verify.
All I am doing is comparing the first index to the last and the second index to the second last and so on.
Hope that helps.
Check Counter from collections
from collections import Counter
def is_palindrome(letters):
return len([v for v in Counter(letters).values() if v % 2]) <= 1
Here is another solution I came up with:
###Piece of code to find the palindrome####
def palindrome():
Palindromee = input("Enter the palindrome \t:")
index = 0
length = len(Palindromee)
while index < length:
if Palindromee[0] == Palindromee[-1] :
index +=1
print ("Palindrome worked as expected")
palindrome()
Simple way to write palindrome
a=raw_input("Enter the string : ") # Ask user input
b= list(a) # convert the input into a list
print list(a)
b.reverse() # reverse function to reverse the
# elements of a list
print b
if list(a) == b: # comparing the list of input with b
print("It is a palindrome")
else:
print("It is not a palindrome")
we could use reverse String function to verify Palindrome:
def palindrome(s):
str=s[::-1]
if s==str:
return True
else:
return False
palindrome('madam')
you can as well try this
def palindrome(str1):
return str1==str1[::-1]
print(palindrome(str1)
the answer above returns a boolean according to the string given
if it is a palindrome prints true else false
I'm just getting started in python, and I'm trying to test a user-entered string as a palindrome. My code is:
x=input('Please insert a word')
y=reversed(x)
if x==y:
print('Is a palindrome')
else:
print('Is not a palindrome')
This always returns false because y becomes something like <reversed object at 0x00E16EF0> instead of the reversed string.
What am I being ignorant about? How would you go about coding this problem?
Try y = x[::-1]. This uses splicing to get the reverse of the string.
reversed(x) returns an iterator for looping over the characters in the string in reverse order, not a string you can directly compare to x.
reversed returns an iterator, which you can make into a string using the join method:
y = ''.join(reversed(x))
For future reference, a lambda from the answers above for quick palindrome check:
isPali = lambda num: str(num) == str(num)[::-1]
example use:
isPali(9009) #returns True
Try this code.
def pal(name):
sto_1 = []
for i in name:
sto_1.append(i)
sto_2 = []
for i in sto_1[::-1]:
sto_2.append(i)
for i in range(len(name)):
if sto_1[i] == sto_2[i]:
return "".join(sto_1), "".join(sto_2)
else:
return "no luck"
name = raw_input("Enter the word :")
print pal(name)
list(reverse( mystring )) == list( mystring )
or in the case of numbers
list(reverse( str(mystring) )) == list( str(mystring) )
Try this code:
def palindrome(string):
i = 0
while i < len(string):
if string[i] != string[(len(string) - 1) - i]:
return False
i += 1
return True
print palindrome("hannah")
Try this code to find whether original & reverse are same or not:-
if a == a[::-1]:
#this will reverse the given string, eventually will give you idea if the given string is palindrome or not.