Python format inside brackets - python

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
>>>

Related

Python re.sub() is not substituting a string

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.

trouble formatting serial data from python enumeration

So I get a list of mentions from twitter, and need to know the index of each mention. To do this I use:
for idx, result in enumerate(mentions, start = 48):
message = result['text']
print idx, message
which returns
48 " first message"
as expected. However, I need to use this index for some serial data that requires me to convert the index into hex. So.. I use:
hidx = hex(idx)
which then returns 0x30. However I need to somehow have this result in the exact format of "\x30" so that I can use serial to write:
serial.write("\x30")
what is the best way to accomplish this? If I keep my hex-converted index code the way it is, I get that pesky extra 0 and no backslash that causes the serial code to actually write serial.write(0x30), which is not what I need. Im hoping to find a way that, because of the for loop, I will receive:
serial.write("\x30")
serial.write("\x31")
serial.write("\x32")
ect. for as many mentions as I need.
Is there a way to strip the first zero and add the \? Maybe a better way? Im new to python and serial communication so any help will be much appreciated.
(Assuming Python 2) "\x30" is a 1-byte string and the byte in question is the one at ASCII code 48:
>>> print repr('\x30')
'0'
So, all you need to do to emit it is serial.write(chr(idx)) -- no need to mess with hex!

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.

Wrap long python strings correctly for optparse

How can I automatically wrap long python strings so that they print correctly?
Specifically, I am trying to add help strings with optparse which I want to be able to modify easily.
I have found several methods of dealing with long strings, none of which allow me to refill after making changes using M-q in emacs or similar:
p.add_option('-a', help = "this is my\
long help text")
forces newlines in the result and doesn't allow refilling
p.add_option('-a', help = "this is my "
"long help text")
formats correctly but doesn't allow refilling
p.add_option('-a', help = '''
this is my
long help text
''')
formats incorrectly but does allow refilling
p.add_option('-a', help = dedent('''
this is my
long help text
'''))
is the best option I've found, formats almost correctly and allows refilling but results in an additional space at the beginning of the string.
The docs use dedent so it seems reasonable, especially if it works. If you want to drop the leading space you could:
help = dedent('''
this is my
long help text
''')[1:]
although
dedent(…).lstrip()
might be more obvious.
Use argparse instead of optparse, if you are using Python >= 2.7. It does dedent for you. You can just do:
parser.add_argument('--argument', '-a', help='''
this is my
long help text
''')
Even if you are using Python < 2.7, you can install argparse from pypi.
Note that there is a way to suppress this auto-dedent behavior. The link given by #msw is actually the section about it.
I'm not 100% sure what refilling is, but here's what I typically use:
p.add_option('-a', help = ("this is my "
"long help text"))
(note the additional parenthesis). Emacs lines up the next line with the previous open parenthesis for me.

How to remove ^M from a text file and replace it with the next line

So suppose I have a text file of the following contents:
Hello what is up. ^M
^M
What are you doing?
I want to remove the ^M and replace it with the line that follows. So my output would look like:
Hello what is up. What are you doing?
How do I do the above in Python? Or if there's any way to do this with unix commands then please let me know.
''.join(somestring.split(r'\r'))
or
somestring.replace(r'\r','')
This assumes you have carriage return characters in your string, and not the literal "^M". If it is the literal string "^M" then substiture r'\r' with "^M"
If you want the newlines gone then use r'\r\n'
This is very basic string manipulation in python and it is probably worth looking at some basic tutorials http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html
And as the first commenter said its always helpful to give some indication of what you have tried so far, and what you don't understand about the problem, rather than asking for an straight answer.
Try:
>>> mystring = mystring.replace("\r", "").replace("\n", "")
(where "mystring" contain your text)
use replace
x='Hello what is up. ^M\
^M\
What are you doing?'
print x.replace('^M','') # the second parameter insert what you want replace it with

Categories