i'm looking for verification for the following
count(i) function of Python range() counts the number of occurrences of the value i in the range it runs on, and thus returns either 0 or 1-- nothing else.
found no hint to anything otherwise in the docs read and the runs I made. wanna verify still-- a bit odd.
It is because range() objects conform to the Sequence ABC, and that ABC has a count() method.
So it is there just for completeness sake, so that the object qualifies as a sequence.
Also see the following link that it states the methods range has due to it being part of the Sequence ABC https://docs.python.org/3/library/stdtypes.html#typesseq
Related
print("abc".replace("","|")) #Explain this
#|a|b|c|
print("".replace("","abc"))
#abc
print("".replace("","abc",3))
#no output why? is this bug ?
I am really unable to understand this lines please explain it breefly...
In the first line you're trying to replace each nothing character with |, so the output should be and is a|b|c . If your code was like a b c, then your output would be |a| |b| |c|
Regarding the last line and your expected output which should be abcabcabc, the replace function replaces, not multiplies. So you can modify your code to thing like this, that first of all you replace your desired characters and then multiply them by 3 to reach what you want.
print("".replace("", "abc")*3)
Output is now abcabcabc.
But about your code, your telling Python interpreter that hey, find three '' and replace them by 'abc', but your code includes only one nothing and you cannot replace 3 of nothing by abc and get empty value.
That is not a bug in fact.
Edit
I searched a bit more and figured out Issue 28029 was a bug like your case in Python Bugs in Python version 3.8. I checked it again with Python 3.9 IDLE and now it is working fine:
print(''.replace('', 'abc', 3))
abc
According to doc (help(str.replace)):
replace(self, old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
Basically you're setting the limit of occurences to be replaced.
For what concern the first example:
it seems that print("abc".replace("","|")) fall in a special case handle by python developers like that. Checking the code here zero length special-case.
You switch from python to c, there you can read that when the string to be replaced has 0 length the function stringlib_replace_interleave is called.
The example said it will:
/* insert the 'to' bytes everywhere. */
/* >>> b"Python".replace(b"", b".") */
/* b'.P.y.t.h.o.n.' */
For all the other cases you can check string replace implementation.
I'm dealing with a Yacc (the ply one) and I have no idea how to make more occurrences of a parsing item without making the program crashing due to infinite recursion.
Let's say I have:
def p_Attribute(p):
''' Attribute : STRING
| NUMBER
| Attribute
| empty '''
[do stuff]
NOTE:
The question is similar to: Python PLY zero or more occurrences of a parsing item but the solution proposed there is not working, I always have infinite recursion.
The problem here is actually in your grammar. Yacc-like parsers don't work with this kind of rule as it requires reducing an Attribute to reduce an Attribute, hence the infinite recursion. (Edit to add note: it would be OK if the right hand Attribute had some non-empty non-ambiguous token required, e.g., Attribute : STRING | NUMBER | '$' Attribute | empty is parseable and allows any number of $ signs in front of the other acceptable Attributes. But as it is, both alternatives, Attribute and empty, can be completely empty. That's a reduce/reduce conflict and it resolves badly here. I think the reduce/reduce conflict might resolve "as desired" if you put the empty rule first—but that's still the "wrong way" to do this, in general.)
Presumably you want one of three things (but I'm not sure which, so imagine the parser generator's confusion :-) ):
zero or more Attributes in sequence (equivalent to regexp-like "x*")
one or more Attributes in sequence (equivalent to regexp-like "x+")
zero or one Attribute, but no more (equivalent to regexp-like "x?")
For all three of these you should, in general, start by defining a single non-terminal that recognizes exactly one valid attribute-like-thing, e.g.:
Exactly_One_Attribute : STRING | NUMBER
(which I'm going to just spell Attribute below).
Then you define a rule that accepts what you intend to allow for your sequence (or optional-attribute). For instance:
Zero_Or_More_Attributes : Zero_Or_More_Attributes Attribute | empty
(This uses "left recursion", which should be the most efficient. Use right recursion—see below—only if you really want to recognize items in the other order.)
To require at least one attribute:
One_Or_More_Attributes: One_Or_More_Attributes Attribute | Attribute
(also left-recursive in this example), or:
Attribute_opt : empty | Attribute
which allows either "nothing" (empty) or exactly one attribute.
The right-recursive version is simply:
Zero_Or_More_Attributes : Attribute Zero_Or_More_Attributes | empty
As a general rule, when using right recursion, the parser winds up having to "shift" (push onto its parse stack) more tokens. Eventually the parser comes across a token that fails to fit the rule (in this case, something not a STRING or NUMBER) and then it can begin reducing each shifted token using the right-recursive rule, working on the STRING-and-NUMBERs right to left. Using left recursion, it gets to do reductions earlier, working left to right. See
http://www.gnu.org/software/bison/manual/html_node/Algorithm.html#Algorithm for more.
I need to enter a complex string for handling (UTC time code) and breaking down as part of an assignment. I have started the function like this as required:
def convertWmiDateTime(wmiDateTime):
But when I enter this:
convertWmiDateTime(20061122185433.000000+600)
The variable wmiDateTime stores 2.0061122186e+13
If I use raw_input the value 20061122185433.000000+600 will be stored correctly in wmiDateTime, but not when its called as intended above.
Is there a way to preserve what was typed into the input? A way to stop Pythong calculating and simplifying the number? vb. net would be something like (wmiDateTime As String) is there anything like that for Python?
Thanks for looking.
Your function requires a string as its input parameter. You can't call it with a number (as you're doing).
raw_input() returns a string, so the equivalent would be to call
convertWmiDateTime("20061122185433.000000+600")
Your version treats the time code as a floating point number which a) doesn't have the required precision to preserve all the digits and b) will get the timezone info (+600) added, which leads to wrong results as well.
I am trying to write a small Python 2.x API to support fetching a
job by jobNumber, where jobNumber is provided as an integer.
Sometimes the users provide ajobNumber as an integer literal
beginning with 0, e.g. 037537. (This is because they have been
coddled by R, a language that sanely considers 037537==37537.)
Python, however, considers integer literals starting with "0" to
be OCTAL, thus 037537!=37537, instead 037537==16223. This
strikes me as a blatant affront to the principle of least
surprise, and thankfully it looks like this was fixed in Python
3---see PEP 3127.
But I'm stuck with Python 2.7 at the moment. So my users do this:
>>> fetchJob(037537)
and silently get the wrong job (16223), or this:
>>> fetchJob(038537)
File "<stdin>", line 1
fetchJob(038537)
^
SyntaxError: invalid token
where Python is rejecting the octal-incompatible digit.
There doesn't seem to be anything provided via __future__ to
allow me to get the Py3K behavior---it would have to be built-in
to Python in some manner, since it requires a change to the lexer
at least.
Is anyone aware of how I could protect my users from getting the
wrong job in cases like this? At the moment the best I can think
of is to change that API so it take a string instead of an int.
At the moment the best I can think of is to change that API so it take a string instead of an int.
Yes, and I think this is a reasonable option given the situation.
Another option would be to make sure that all your job numbers contain at least one digit greater than 7 so that adding the leading zero will give an error immediately instead of an incorrect result, but that seems like a bigger hack than using strings.
A final option could be to educate your users. It will only take five minutes or so to explain not to add the leading zero and what can happen if you do. Even if they forget or accidentally add the zero due to old habits, they are more likely to spot the problem if they have heard of it before.
Perhaps you could take the input as a string, strip leading zeros, then convert back to an int?
test = "001234505"
test = int(test.lstrip("0")) # 1234505
I am trying to port some Python code and I am a little lost on small issue which I would appreciate some advice.
I understand the in operator but I am a little unclear on what the : operator does in this example.
if foo in bar[i][:2]:
# do something
In http://docs.python.org/tutorial/introduction.html#strings it states that the : operator makes the first two characters only if this is a string. However when used with a list like this is that what will happen as well? So does this just mean the first 2 characters of the string in th
This is called list slicing, you already link to the proper part of the documentation in your question. If you find documentation confusing, there is a video tutorial for that:
http://www.youtube.com/watch?v=iD6a0G8MnjA
The behaviour of the operator doesn't depend on where its operands come from - it doesn't matter whether it was a literal, a variable, or a complex expression. The operator does its thing because its operand is a string, not because it was computed in a particular way.