I need a code to replace this..
import _mysql
a = "111"
a = _mysql.escape_string(a)
"a" is always gonna be a number between 1 and 1000+
and thus maybe there is a more secure way to "cleaning up" the "a" string in this example for mysql and etc..
rather than relying on
_mysql.escape_string()
function.
which we have no idea what it even does. or how it works. perhaps would be slower than something that we can invent given that all we are working is a number between 1 and 1000+
RE-PHRASÄ°NG THE QUESTÄ°ON:
How to ask python if the string is a maximum of 4 digit number"
Check if it's a number:
>>> "1234".isdigit()
True
>>> "ABCD".isdigit()
False
Check its length:
>>> 1 <= len("1234") <= 4
True
>>> 1 <= len("12345") <= 4
False
escape_string won't clean your string. From the docs:
"escape_string(s) -- quote any SQL-interpreted characters in string s.
Use connection.escape_string(s), if you use it at all. _mysql.escape_string(s) cannot handle character sets. You are probably better off using connection.escape(o) instead, since
it will escape entire sequences as well as strings."
Related
I'm trying to efficiently add one to the end of a string like this:
tt0000001 --> tt0000002 but I'm not sure how to accomplish this.
A complicated way of doing this is to remove the 2 t's at the beginning, count the number of non-zero digits (let's call that number z), make the string an int, add 1, and then create a string with 2 t's, 6 - z 0's, and then the int, but since I need to use many strings (ex: tt0000001, then tt0000002 then tt0000003, etc) many times, it would be great to have a more efficient way of doing this.
Would anyone know how to do this? A one-liner would be ideal if possible.
Thank you!
What you describe is essentially correct. It's not as difficult as you suggest, though, as creating a 0-padded string from an integer is supported.
As long as you know that the number is 7 digits, you can do something like
>>> x = 'tt0000001'
>>> x = f'tt{int(x.lstrip("t"))+1:07}'
>>> x
'tt0000002'
Even simpler, though, is to keep just an integer variable, and only (re)construct the label as necessary each time you increment the integer.
>>> x = 1
>>> x += 1
>>> f'tt{x:07}'
'tt0000002'
>>> x += 1
>>> f'tt{x:07}'
'tt0000003'
I use python 2.7 and windows.
I want to convert string'A123456' to bytes: b'\x0A\x12\x34\x56' and then concatenate it with other bytes (b'\xBB') to b'\xbb\x0A\x12\x34\x56'.
That is, I want to obtain b'\xbb\x0A\x12\x34\x56' from string'A123456' and b'\xBB'
This isn't too hard to do with binascii.unhexlify, the only problem you've got is that you want to zero pad your string when it's not an even number of nibbles (unhexlify won't accept a length 7 string).
So first off, it's probably best to make a quick utility function that does that, because doing it efficiently isn't super obvious, and you want a self-documenting name:
def zeropad_even(s):
# Adding one, then stripping low bit leaves even values unchanged, and rounds
# up odd values to next even value
return s.zfill(len(s) + 1 & ~1)
Now all you have to do is use that to fix up your string before unhexlifying it:
>>> from binascii import unhexlify
>>> unhexlify(zeropad_even('A123456'))
'\n\x124V'
>>> _ == b'\x0A\x12\x34\x56'
True
I included that last test just to show that you got the expected result; the repr of str tries to use printable ASCII or short escapes where available, so only the \x12 actually ends up in the repr; \x0A' becomes \n, \x34 is 4 and \x56 is V, but those are all equivalent ways to spell the same bytes.
I have a long list of suburbs that I want to do something to
A LOT of them have RDx (for rural Delivery) where x is a number from 1 to 30
I want to just get rid of the RDx like below
for row in WorkingData['PatientSuburb']:
if 'RD10' in str(row):
WorkingData['PatientSuburb'].replace(regex=True,inplace=True,to_replace=r'RD10',value=r'')
I was thinking If I could run a loop and increment the number somehow that'd be great. this wouldn't work but it's along the lines of what I'd like to do:
for rd in range(1,31,1):
if 'RD',rd in str(row):
WorkingData['PatientSuburb'].replace(regex=True,inplace=True,to_replace=r'RD'rd ,value=r'')
If I do this I get output with a space in between:
for rd in range(1,31,1):
print 'RD',rd
like so:
RD 1
RD 2
RD 3
RD 4
RD 5
RD 6
RD 7
RD 8
RD 9
RD 10
RD 11
RD 12
and also I would need to figure out how this piece would work...
to_replace=r'RD'rd
I have seen someone use a % sign in labelling a plot & then it brings in a value from outside the quotes - but I don't know if that's a part of the label function (I did try it and that didn't work at all)
That would look like this
to_replace=r'RD%' % rd
Any help on this would be great thanks!
If you want to use a for loop and substitute a substring by the index then I would say you are almost there.
to_replace = 'RD%d' % i
'%' marks the start of the specifier. In the example above, "d" follows "%" which means to place here a signed integer decimal. It's the same as "printf" library function in C. If "%" is not followed by any valid conversion character, it won't change anything regardless of what's on the right-hand side.
More details and examples here: https://docs.python.org/3.6/library/stdtypes.html#printf-style-bytes-formatting
Even though your question is about looping over several integers to generate strings, it seems your problem would actually be more suited for a regular expression.
This would allow you to capture multiple cases in one, without looping over possible values.
>>> import re
>>> RD_PATTERN = re.compile(r'RD[1-3]?[0-9]')
>>>
>>> def strip_rd(string):
... return re.sub(RD_PATTERN, '', string)
...
>>>
>>> strip_rd('BlablahRD5')
'Blablah'
>>> strip_rd('BlablahRD5sometext')
'Blablahsometext'
>>> strip_rd('BlablahRD10sometext')
'Blablahsometext'
>>> strip_rd('BlablahRD25sometext')
'Blablahsometext'
The regex I provided is not rock-solid by any means (e.g. it matches RD0 even though you specified [1..30]), but you can create one that fits your specific use case. For instance, it might make sense to check that the pattern is at the end of the string, if that's expected to be the case.
Also, note that re.compile-ing the pattern is not necessary (you can give the pattern string directly), but since you mentioned you have several rows, it'll be more performant.
i want to make a calculator to "/","*",and "+" so i write my code like that
x,op,y=raw_input()
if op=='+':
print int(x)+int(y)
here if i enter number have two digit it will make error i should enter digit less than 10 form 0 to 9 only to make plus or minus and so on so i tried to split them like this
x,op,y=raw_input().split()
if op=='+':
print int(x)+int(y)
put the input will be like 20 + 20 here is the problem i want to remove this space between the number more than 9 to make the operation i want the input like 20+20 not 20 + 20 on them so i can submit the code on the online judge help me please
Do you actually need to parse the expression yourself? What about
expression = raw_input()
answer = eval(expression)
print answer
?
You could use try: and catch exceptions and do something sensible if the default exception raising isn't the behavior you want. (Like, for instance, if the expression ends up being asdf'.8 or some other garbage expression, you might want a different behavior from the default SyntaxError.)
Note: a criticism of the approach I suggest above is it allows potentially malicious strings to be evaluated, so it might make sense to sanitize your input first...
try re.split("([+-/*])",raw_input()) maybe ?
my_input = raw_input()
numbers = re.split("([+-/*])", my_input)
if '+' in my_input:
print float(numbers[0]) + float(numbers[1])
or
>>> import re
>>> re.split("\s*([+-/*])\s*",raw_input())
29+ 22
['29', '+', '22']
I am trying to test a basic premise in python and it always fails and I can't figure out why.
My sys.argv looks like this:
['test.py', 'test']
And my code looks like this:
if len(sys.argv) > 1 and sys.argv[1] is 'test':
print 'Test mode'
But the test is never true. I am sure that I am missing something really simple here, but I can't figure out what it is.
As mentioned above, the main reason is your test comparison. Using is is different than using == as it compares if two objects are equal. In this case, you can verify that they are not equal by checking their ids:
import sys
print id(sys.argv[1])
print id('test')
My output:
140335994263232
140335994263424
As they point to different objects, they will not be equal when using is (but using == will compare the strings themselves, which will return True).
The issue at work here is the concept of interning. When you hardcode two identical strings into your source, the strings are interned and the two will share an object ID (this explains #SamMussmann's very valid point below). But when you pass a string in via argv, a new object is created, thereby making the comparison to an identical hardcoded string in your code return False. The best explanation I have found so far is in here, where both Alex Martelli and Jon Skeet (two very reputable sources) explain interning and when strings are interned. From these explanations, it does seem that since the data from argv is external to the program, the values aren't interned, and therefore have different object IDs than if they were both literals in the source.
One additional point of interest (unrelated to the issue at hand but pertinent to the is discussion) is the caching that is done with numbers. The numbers from -5 to 256 are cached, meaning that is comparisons with equal numbers in that range will be True, regardless of how they are calculated:
In [1]: 256 is 255 + 1
Out[1]: True
In [2]: 257 is 256 + 1
Out[2]: False
In [3]: -5 is -4 - 1
Out[3]: True
In [4]: -6 is -5 - 1
Out[4]: False