Python re.sub() is not substituting a string - python

Hey Guys Need Your Help Here.
This is my sample code
import random
import string
import re
str=r'im a boy \\x%02X'
result = re.sub('\\\\x%02X', re.escape('\x5c\x5c\x78\x25\x30\x32\x58'), str, 0)
print(" Code=\n", result)
So when i took output from this program. The output is:
Code=
im a boy \\x%02X
But it is supposed to be like this/
Code=
im a boy \x5c\x5c\x78\x25\x30\x32\x58
Why it is not replacing??

There's a number of mistakes in your code, which makes me wonder if r'im a boy \\x%02X' is actually a correct representation of your input.
Assuming it is:
import re
s = r'im a boy \\x%02X'
result = re.sub(r'\\\\x%02X', re.escape(r'\x5c\x5c\x78\x25\x30\x32\x58'), s)
print(result)
Some of the problems with your code:
Why is random in there? And string?
Don't name variables so that they shadow basic types (or any builtins), str is a bad name
Without the r the \x5c[etc] string will turn into the exact same string as you had before, defined as bytes.
Why use the byte representation of the exact same text as a the replacement for the text?
Why tell re.sub to only replace 0 times?
By the way, from what you appear to be trying here, I wonder if you realise that what you're printing and what the actual value of a variable is, isn't exactly the same thing. What you print is the text representation of the value, not the actual value.
You would do well to explain why you're attempting this replacement, as this may be a typical XY problem.

Related

Using string templates for making a quine in python?

I'm basically trying to make a quine in python and first tried with f-strings, but I quickly realized that I first have to define the variables I want to format inside the string. I then learned about string templates and figured that would be the way to go. I am however not that experienced with it and could need some help. Any suggestions?
Here's the actual code:
from string import Template
s="from string import Template\ns=$s\nt=Template($s).substitute(s=$s)\nprint($s)"
t=Template(s).substitute(s=s)
print(s)
It gives me somewhat of the right result. The only problem is that it's not replacing the $s with the actual string. I've might just have misunderstood the whole concept with quines and the method of doing them but I feel this should work.
Output:
from string import Template
s=$s
t=Template($s).substitute(s=$s)
print($s)
I'm not sure how this would be done using string.Template, but you could use str.format as a straightforward replacement to f-strings that suits this task, as it allows you to delay the interpolation of the s variable:
s='s={0!r}\nprint(s.format(s))'
print(s.format(s))
Output:
s='s={0!r}\nprint(s.format(s))'
print(s.format(s))
The !r is used to get the repr of s, which wraps it in quotes, and escapes the newlines.
I've taken the advice from #Will Da Silva and included the repr() function in my method of doing it as seen below:
from string import Template
s='from string import Template\ns=$s\nt=Template(s)\nprint(t.substitute(s=repr(s)))'
t=Template(s)
print(t.substitute(s=repr(s)))
I think the problem was that it interpreted the string as code and in turn made a new line at every \n. But now when it keeps the quotation marks it just sees it as a string.

How do I write urilify string python

Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string.
This is how I tried to solve, but I know I haven't addressed the question correctly where author asks us to assume the additional space at the end and the true length of the string. I am a beginner in programming trying to learn Algorithms and DS, quite a head bagging on this side.
def replace(astring):
alist= list(astring)
for i in range(len(alist)):
if alist[i] == ' ':
alist[i]= '%20'
return (''.join(alist))
print(replace("Mr John Smith "))
Since you are trying to learn algorithms, I think it will be beneficial to leave two hints to help you forward instead of the answer
"Mr John Smith ".rstrip() will strip any space at the end of a string. This means you will not have to worry about any logic for whitespace
Even though the solution works, you are using extra space by creating alist. Maybe try replacing things in the string itself? In Python a string can already by accessed as a string. For example astring[:2] is valid. Also 'hello world!'.replace(' ', 'test') is your friend
You can use the following code :
import urllib.parse
urllib.parse.quote("Mr John Smith ")

Python: check if string meets specific format

Programming in Python3.
I am having difficulty in controlling whether a string meets a specific format.
So, I know that Python does not have a .contain() method like Java but that we can use regex.
My code hence will probably look something like this, where lowpan_headers is a dictionary with a field that is a string that should meet a specific format.
So the code will probably be like this:
import re
lowpan_headers = self.converter.lowpan_string_to_headers(lowpan_string)
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(lowpan_headers[dest_addrS])
However, my issue is in the format and I have not been able to get it right.
The format should be like bbbb00000000000000170d0000306fb6, where the first 4 characters should be bbbb and all the rest, with that exact length, should be hexadecimal values (so from 0-9 and a-f).
So two questions:
(1) any easier way of doing this except through importing re
(2) If not, can you help me out with the regex?
As for the regex you're looking for I believe that
^bbbb[0-9a-f]{28}$
should validate correctly for your requirements.
As for if there is an easier way than using the re module, I would say that there isn't really to achieve the result you're looking for. While using the in keyword in python works in the way you would expect a contains method to work for a string, you are actually wanting to know if a string is in a correct format. As such the best solution, as it is relatively simple, is to use a regular expression, and thus use the re module.
Here is a solution that does not use regex:
lowpan_headers = 'bbbb00000000000000170d0000306fb6'
if lowpan_headers[:4] == 'bbbb' and len(lowpan_headers) == 32:
try:
int(lowpan_headers[4:], 16) # tries interpreting the last 28 characters as hexadecimal
print('Input is valid!')
except ValueError:
print('Invalid Input') # hex test failed!
else:
print('Invalid Input') # either length test or 'bbbb' prefix test failed!
In fact, Python does have an equivalent to the .contains() method. You can use the in operator:
if 'substring' in long_string:
return True
A similar question has already been answered here.
For your case, however, I'd still stick with regex as you're indeed trying to evaluate a certain String format. To ensure that your string only has hexadecimal values, i.e. 0-9 and a-f, the following regex should do it: ^[a-fA-F0-9]+$. The additional "complication" are the four 'b' at the start of your string. I think an easy fix would be to include them as follows: ^(bbbb)?[a-fA-F0-9]+$.
>>> import re
>>> pattern = re.compile('^(bbbb)?[a-fA-F0-9]+$')
>>> test_1 = 'bbbb00000000000000170d0000306fb6'
>>> test_2 = 'bbbb00000000000000170d0000306fx6'
>>> pattern.match(test_1)
<_sre.SRE_Match object; span=(0, 32), match='bbbb00000000000000170d0000306fb6'>
>>> pattern.match(test_2)
>>>
The part that is currently missing is checking for the exact length of the string for which you could either use the string length method or extend the regex -- but I'm sure you can take it from here :-)
As I mentioned in the comment Python does have contains() equivalent.
if "blah" not in somestring:
continue
(source) (PythonDocs)
If you would prefer to use a regex instead to validate your input, you can use this:
^b{4}[0-9a-f]{28}$ - Regex101 Demo with explanation

Python format inside brackets

Is it possible to format inside of the brackets? What I mean is this:
print "Formatting: { 0 : {1} s }".format("""\
long piece of text that I need to format, but I can't explicitly say\
how long it is going to be because it is coming from another function\
that gives me the length of how many characters I can print. So, it would be\
really helpful if someone could help me with this""" , charMax())
import random
def charMax():
return random.randint(10, 80)
Can anyone help me establish how to emulate the sudo code above?
Your formatting specifier is wrong. String length restriction is governed by the precision.
"{0:.{1}s}".format(...)
Better to put the length in first, and use the .length precision formatting to limit the length:
"Formatting: {1:.{0}s}".format(charMax(), """Some long string""")
Now the string is formatted to a maximum length rather than a minimum:
>>> some_long_string = """\
... long piece of text that I need to format, but I can't explicitly say\
... how long it is going to be because it is coming from another function\
... that gives me the length of how many characters I can print. So, it would be\
... really helpful if someone could help me with this"""
>>> print "Formatting: {1:.{0}s}".format(charMax(), some_long_string)
Formatting: long piece of text that I need to format, bu
>>> print "Formatting: {1:.{0}s}".format(charMax(), some_long_string)
Formatting: long piece of text that I need to format, but I can't explicitly
>>> print "Formatting: {1:.{0}s}".format(charMax(), some_long_string)
Formatting: long piece of text that I
It'll work with the orders reversed too:
>>> print "Formatting: {0:.{1}s}".format(some_long_string, charMax())
Formatting: long piece of text that I need to format, but I can't ex
But its clearer for the reader to see what is happening the other way around.
You most likely need a function if you want a string of desired length, formats aren't going to do much for you:
def charMax():
return random.randint(10, 80)
def stringLength(originalStr, length):
return originalStr[:length]
And then you can do the formatting:
print "Formatting: {0}".format(stringLength("long piece of text that I need to format, but I can't explicitly say how long it is going to be because it is coming from another function that gives me the length of how many characters I can print. So, it would be really helpful if someone could help me with this", charMax()))
>>> print "Formatting: {0}".format(stringLength("long piece of text that I need to format, but I can't explicitly say how long it is going to be because it is coming from another function that gives me the length of how many characters I can print. So, it would be really helpful if someone could help me with this", charMax()))
Formatting: long piece of text that I need to format,
>>> print "Formatting: {0}".format(stringLength("long piece of text that I need to format, but I can't explicitly say how long it is going to be because it is coming from another function that gives me the length of how many characters I can print. So, it would be really helpful if someone could help me with this", charMax()))
Formatting: long piece of text that I n
>>> print "Formatting: {0}".format(stringLength("long piece of text that I need to format, but I can't explicitly say how long it is going to be because it is coming from another function that gives me the length of how many characters I can print. So, it would be really helpful if someone could help me with this", charMax()))
Formatting: long piece of text that I need to format, but I can't expl
>>> print "Formatting: {0}".format(stringLength("long piece of text that I need to format, but I can't explicitly say how long it is going to be because it is coming from another function that gives me the length of how many characters I can print. So, it would be really helpful if someone could help me with this", charMax()))
Formatting: long piece of text that I nee
>>>

Python: Separating string into individual letters/words to be converted into ascii-hex or ascii-dec

As the title suggests, I want to get a string, split it into individual bits to input into something like ord('') and get a value for each individual character in that string. Still learning python so things like this get super confusing :P. Furthermore, the process for encryption for each of the codes will just be to shift the alphabet's dec number by a specified value and decrypt into the shifted value, plus state that value for each character. How would i go about doing this? any and all help would be greatly appreciated!
message=input("Enter message here: ", )
shift=int(input("Enter Shift....explained shift: ", )
for c in list(message):
a=ord(c)
print c
This is the very basic idea of what i was doing (was more code but similar), but obviously it didn't work :C, the indented--> just means that it was indented, just don't know how to do that in stack overflow.
UPDATE: IT WORKS (kinda) using the loop and tweaking it according to the comments i got a list of every single ascii dec value for each character in the string!, ill try and use #Hugh Bothwell's suggestion within the loop and hopefully get some work done.
mystring = "this is a test"
shift = 3
encoded = ''.join(chr(ord(ch) + shift) for ch in mystring)
You'll have to do a little more if you want your alphabet to wrap around, ie encode('y') == 'b', but this should give you the gist of it.

Categories