In my program I want to check if the stroke symbol is a common digit (0-9)
.isnumeral works strange because it counts alphabeticals (a-z) as True, well then I lurked in and got that .isnumeral isn't actually searching exclusively for what I want - digits. And through the manual I found .isdigit but:
dna = 'a3'
start = 0
end = 1
if dna[end].isdigit is True:
print('Yes')
It's not working and 'Yes' isn't showing as expected.
if dna[end].isdigit is True:
isdigit() is a function, not an attribute.
You forgot the parentheses on the end, therefore you're referring to the function object itself, instead of the result of calling the function.
You must actually call the isdigit() method:
dna = 'a3'
start = 0
end = 1
if dna[end].isdigit():
print('Yes')
This gives your expected answer, True.
If you do dna[end].isdigit it just gives an object <built-in method isdigit of str object at address> which won't evaluate.
dna[end].isdigit in this case is referring to a str.isdigit function.
If you do print(type(dna[end].isdigit)) you will see what I mean.
To call the function instead, add paranthesis like this if dna[end].isdigit():
Two things:
there's no need to compare to true, just use the result from isdigit()
isdigit() is a function, which is truthy on its own, but does not equate to True
Check out the Python docs for more info.
Related
str = "chair table planttest"
substr = ["plant", "tab"]
x = func(substr, str)
print(x)
I want code that will return True if str contains all strings in the substr list, regardless of position. If str does not contain all the elements in substr, it should return False.
I have been trying to use re.search or re.findall but am having a very hard time understanding regex operators.
Thanks in advance!
You need to loop through all of the substrings and use the in operator to decide if they are in the string. Like this:
def hasAllSubstrings(partsArr, fullStr):
allFound = true
for part in partsArr:
if part not in fullStr:
allFound = false
return allFound
# Test
full = "chair table planttest"
parts = ["plant", "tab"]
x = hasAllSubstrings(parts, full)
print(x)
Let's see what the hasAllSubstrings function.
It creates a boolean variable that decides if all substrings have been found.
It loops through each part in the partsArr sent in to the function.
If that part is not in the full string fullStr, it sets the boolean to false.
If multiple are not found, it will still be false, and it won't change. If everything is found, it will always be true and not false.
At the end, it returns whether it found everything.
After the function definition, we test the function with your example. There is also one last thing you should take note of: your variables shouldn't collide with built-ins. You used the str variable, and I changed it to full because str is a (commonly used) function in the Python standard library.
By using that name, you effectively just disabled the str function. Make sure to avoid those names as they can easily make your programs harder to debug and more confusing. Oh, and by the way, str is useful when you need to convert a number or some other object into a string.
You can simply use the built-in function all() and the in keyword:
fullstr = "chair table planttest"
substr = ["plant", "tab"]
x = all(s in fullstr for s in substr)
In continuation to the answer of # Lakshya Raj, you can add break after allFound = false.
Because, as soon as the first item of the sub_strung is not found in str, it gives your desired output. No need to loop further.
allFound = false
break
First of all, I'm very sorry that I ask about a fairly basic problem.
When I studying syntactic sugar in Python, I found a very interesting syntax like below:
#'FT'[boolean]
print('FT'[False]) # F
print('FT'[True]) # T
print('NY'[False]) # N
print('NY'[True]) # Y
As a combination of 'String' and [square brackets],
If a False boolean value is entered in [square brackets],
the first character of 'String' is returned, and vice versa, the second character of 'String' is returned.
What is the name of this syntax and when did it appear and what is the principle of it?
It's normal indexing. What may be confusing you is the fact that bool is a subclass of int (with True == 1 and False == 0) which means that
'FT'[False]
is equivalent to
'FT'[0]
which is, of course, 'F'.
(You might also not be familiar with indexing a str literal directly, as opposed to a str-valued variable: print('FT'[False]) is the same as
x = 'FT'
print(x[False])
)
I'm new to Python and I'm messing around with this and I don't really know why when I change the brackets to parenthesis I get an error, or why I can't just use len(text - 1).
I'm looking at this code:
def reverse(text):
result = ""
length = len(text)
for i in text:
result += text[length - 1]
length -= 1
return result
Any help with understanding this is greatly appreciated!
Thanks!
You can't use text - 1 because that doesn't make sense; you cannot take 1 from a string.
Now, as for len(...) this is a function so has () for the call rather than []. You pass it the thing you want the length of.
text[length - 1] is indexing into the string, at a position, and follows the list syntax for indexing or sub-scripting.
When you use len(text - 1) you try to subtract int (1) from str (text). It is insupported operation in python (and moreover, impossible). To get a part of string you need you must use text[length - 1].
Python Parentheses
Parentheses play many different roles in Python these are some of the main roles they play:
The mathematical role:
Python parentheses act like parentheses in math as they are at the top of the Python Priority Precedence
This means that this:
>>> 3 + 4 * 2
returns:
12
Whereas with parentheses:
>>> (3 + 4) * 2
returns:
14
But that's not all, their priority also expands to Boolean expressions:
for example:
False and False or True and True
evaluates to True as and is executed before or. However, if you add some parentheses:
False and (False or True) and True
It evaluates to False as the or is executed before the and
Tuple
In python, when you put something in a tuple you use () notation.
Functions
When you declare or call a function you always need to add the parentheses after the function name. Think of them as a basket to put the arguments in. If you forget them the Python interpreter will think that you are calling a variable for example:
list
This is a variable called list and does nothing special
list() #Empty basket
This, however, is a call to a function as there is a "basket"
Square Brackets
Square Brackets also have quite a few roles:
Lists
In python, you use square brackets if you want to declare a list instead of a tuple.
List comprehension
List comprehension is actually pretty complicated so read this for more information but just know that it uses square brackets
Looking up
The main use of square brackets is to look up a value inside a list, tuple, or dictionary. Think of it like the google search bar: you write what you want and it tells you what it has. For example:
tuple = (2, 4)
if you want to get 4 you will need to look up the 2nd value of the tuple:
tuple[1] #The first value is 0
Slicing
Slicing is simply the idea of taking only certain parts of a list (or tuple, dictionary or even string). Here is an explanation by Greg Hewgill (https://stackoverflow.com/a/509295/7541446):
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step
The key point to remember is that the :end value represents the first
value that is not in the selected slice. So, the difference beween end
and start is the number of elements selected (if step is 1, the
default).
The other feature is that start or end may be a negative number, which
means it counts from the end of the array instead of the beginning.
So:
a[-1] # last item in the array a[-2:] # last two items in the
array a[:-2] # everything except the last two items
Python is kind to the programmer if there are fewer items than you ask
for. For example, if you ask for a[:-2] and a only contains one
element, you get an empty list instead of an error. Sometimes you
would prefer the error, so you have to be aware that this may happen.
I hope this provided useful insight to explaining the difference between parentheses and square brackets.
This means that in your question len() is a function where you are putting text inside the basket. However, when you call text[length-1] you are looking up the value at position length-1
The python builtin function len() returns the length in numbers of the object in argument e.g
temp = [1, 2, 3, 4]
length = len(temp)
then the len() will return 4 in this case. but if someone write
length = len(temp-1)
then
temp-1
is not a valid object, therefor you cannot use it.
The reason you can't do len(text-1) is because text is a string type you are trying to reverse, and being a string you cannot combine it with numbers(unless they are a string, but thats a different story) without getting an error. Therefore you do len(text)-1 because len(text) would equal the length of whatever the text is(lets say four), and then you can subtract 1 from 4 because 4 is an integer.
The reason you need brackets and not parentheses when you are doing text[length-1] is because in python trying to get a single value out of a string requires the use of string[] and putting a position in the string inside the []. You use partakes to call functions like print(string) or len(text), so putting text(length-1) would create an error that basically says the program doesn't have a function named "text" and it doesn't know what to do.
Hope this helps. Tell me if you have any more questions.
Im trying to write a function that get 2 arguments (2 strings actually) and compares them (ignoring the difference in upper/lower cases). For example:
cmr_func('House', 'HouSe')
true
cmr_func('Chair123', 'CHAIr123')
true
cmr_func('Mandy123', 'Mandy1234')
False.
Well, I tried something, but it seems very stupid and bad designed function, which anyway does not work. I would like to get idea. I believe i need to use some built-in str function, but im not sure how they can help me.
I thought about using in function with some loop. But i dont know on what kind of object should i apply a loop.
def str_comp(a,b):
for i in a:
i.lower()
for i in b:
i.lower()
if a == b:
print 'true'
else:
print 'false'
Any hint or idea are welcomed. Thanks :)
You can just convert both strings to lower-case and compare those results:
def str_comp (a, b):
return a.lower() == b.lower()
The idea behind this is normalization. Basically, you want to take any input string, and normalize it in a way that all other strings that are considered equal result in the same normalized string. And then, you just need to compare the normalized strings for equality.
Other operations you might consider are stripping whitespace (using str.strip()), or even more complex operations like converting umlauts to 2-letter combinations (e.g. ä to ae).
The problem with your solution is that you seem to assume that iterating over a string will allow you to modify the characters individually. But strings are immutable, so you cannot modify an existing string without creating a new one. As such, when you iterate over a string using for i in a you get many individual, independent strings for each character which are in no way linked to the original string a. So modifying i will not affect a.
Similarly, just calling str.lower() will not modify the string either (since it’s immutable), so instead, the function will return a new string with all letters converted to lower-case.
Finally, you shouldn’t return a string “True” or “False”. Python has boolean constants True and False which should be used for that. And if you use them, you don’t need to do the following either:
if condition:
return True
else:
return False
Since condition already is interpreted as a boolean, you can just return the condition directly to get the same result:
return condition
First you dont need to iterate the String to make all chars lowercase.
You can just:
a.lower()
b.lower()
Or you can do it all together:
def str_comp(a,b):
return a.lower() == b.lower()
Dont forget you're also returning True or False a Boolean, not returning a String (in this case the string "True" or "False")
If you want to return a String is function would different :
def str_comp(a,b):
if a.lower() == b.lower()
return "True"
return "False"
The function str.lower() actually works in a slightly different way:
This is no in-place modification. Calling a.lower() returns a copy of a with only lowercase letters and does not change a itself.
str.lower() can be called on whole strings, not just characters, so the for i in a loop won't be necessary.
Therefore you could simplify your function like following:
def str_comp(a, b):
if a.lower() == b.lower():
print 'true'
else:
print 'false'
def are_strings_equal(string_1, string_2):
return string_1.lower() == string_2.lower()
>What's wrong with this..
Code-1
def first_last6(nums):
if nums[0]==6 or nums[len(nums)-1] == 6:
return True
else:
return False
Code-2
def first_last6(nums):
return (nums[0]==6 or nums[-1]== 6)
How come both True?
There seem to be two questions inside, so I’ll answer both.
First of all, why are nums[len(nums)-1] and nums[-1] the same? When specifying an index, Python allows you to use negative numbers that are interpreted like this: if i in nums[i] is negative, then the index len(nums)+i is returned. So, basically, [-1] will get the last element, [-2] the second to last etc.
The second question is why the two formats are identical:
if expression:
return True
else
return False
and
return expression
expression in this case is an expression that returns a boolean type, so either True or False. The if statements checks exactly that; if the expression equals to true, it will return true, otherwise (if the expression equals to false) it will return false.
So you can (and should, to make it cleaner) just return the expression itself, as it is already true or false.
In the case expression itself is not a boolean expression, the if statement will still check to what boolean type it would evaluate (for example a non-empty string would be true, or a number other than 0 would be true too). To keep the short syntax, you can then explicitely convert the expression to a boolean value, using bool(expression), as larsmans mentioned in the comments.
nums[-k] is a shorthand for nums[len(nums)-k]. To get the k-th last element you use the notation nums[-k]. Usually it is clear what the notation stands for and the compiler knows how to turn that python code into machine code, which is why certain language contructs are possible and others are not. Other short hands include nums[:k] to get the first k elements, nums[:-k] to get all elements up to the k-th last element etc. Via google, python docs, you will find much more on this. List operations are a great strength of the python.
http://www.diveintopython.net/native_data_types/lists.html
uh, because both are exactly the same and they both evaluate to True.