python Variable in a string - python

I am trying to specify a standard binary format length from a variable but for some reason it never works. Am I doing the formatting wrong or the variable inclusion?
comp.write("{0:%ib}".format(I) % num_bits)
ValueError: Invalid conversion specification

Firstly, it's in the wrong order:
("{0:%ib}" % num_bits).format(I)
Secondly, this isn't the way to do it! Mixing up types of formatting operator implies you don't know it can be done together. You want:
"{:{}b}".format(I, num_bits)
and if you really want to do it in two steps:
"{{:{}b}}".format(num_bits).format(I)
The {{ and }} are escaped, so are transformed to single braces, after the first .format.

You're doing the interpolation the wrong way round. You'll need to resolve the %i before passing it to format. This would work:
comp.write(("{0:%ib}" % num_bits).format(I))
but is pretty horrible, you probably want to split it into two:
fmt = "{0:%ib}" % num_bits
comp.write(fmt.format(I))

Related

is there a way to use numbers in a python array with strings

I get this error from python when I try to run my program does anyone know how to fix it.
ops.append(i+".)"+names[i]+"'s Living Quarters\n")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ops is a array for choices.
names is a array with names to be made in to the ops array with a number for printing.
i is a increasing number for the choice number.
sorry if there have been other questions like this, I couldn't find a solution
You'll need to convert your integer to a string before you can concatenate it. You can do this with str(i).
Or you can accomplish your append line with f-strings, like so:
ops.append(f"{i}.) {names[i]}'s Living Quarters\n")
ops.append(str(i)+".)"+str(names[i])+"'s Living Quarters\n")
Should work!
str(VARIABLE) converts the VARIABLE into STR(String)
You can use an integer in a string by either converting the integer to a string using
str(variable), or by formatting it in the string using F-strings.
String formatting example:
stringName = f"Number: {integer_variable}"
Which can also be used for other variable types and is a bit more readable than concatenating a ton of variables to strings using +
There's lots of fun ways to format strings in Python. I tend to prefer string.format just because of the flexibility.
ops = "{}{}.) {}'s Living Quarters\n".format(ops, i, names[i])
Ideally, you'd include the formatting for ops in there as well, but since I didn't have the code you used to generate it , I just showed you the closest I could.

Using '{' as a string in the format method python

I want to be able to print something like such "{x}" using the format method, but the nature of the curly braces is messing me up.
I tried
'{{}}'.format(x)
however that returned a value error. Is there a way to tell python that the curly brace is meant to be used as a string rather than an argument for the format?
{{ is converted into {by format, so use this:
'{{{}}}'.format(x)
(note the three braces)
However, in this case, I would use the older C-style format string:
'{%s}' % x
It is a lot clearer.

python string formatting {:d} vs %d on floating point number

I realise that this question could be construed as similar to others, so before I start, here is a list of some possible "duplicates" before everyone starts pointing them out. None of these seem to really answer my question properly.
Python string formatting: % vs. .format
"%s" % format vs "{0}".format() vs "?" format
My question specifically pertains to the use of the string.format() method for displaying integer numbers.
Running the following code using % string formatting in the interpreter running python 2.7
>>> print "%d" %(1.2345)
1
Whereas using the string.format() method results in the following
>>> print "{:d}".format(1.2345)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object type 'float'
I was expecting the same behavior in both; for the interpreter to actually convert my floating point number to an integer prior to displaying. I realise that I could just use the int function to convert the floating point number to integer format, but I was looking for the same functionality you get with the %d formatting method. Is there any string.format() method that would do this for me?
The two implementations are quite separate, and some warts in the % implementation were ironed out. Using %d for floats may mask problems in your code, where you thought you had integers but got floating point values instead. Imagine a value of 1.999999 and only seeing 1 instead of 2 as %d truncates the value.
As such, the float.__format__() hook method called by str.format() to do the actual conversion work does not support the d format and throws an exception instead.
You can use the {:.0f} format to explicitly display (rounded) floating point values with no decimal numbers:
>>> '{:.0f}'.format(1.234)
'1'
>>> '{:.0f}'.format(1.534)
'2'
or use int() before formatting to explicitly truncate your floating point number.
As a side note, if all you are doing is formatting a number as a string (and not interpolating into a larger string), use the format() function:
>>> format(1.234, '.0f')
'1'
This communicates your intent better and is a little faster to boot.
There is an important change between 2.7 and 3.0 regarding "automatic type conversion" (coercion). While 2.7 was somehow relatively "relax" regarding this, 3.0 forces you to be more disciplined.
Automatic conversion may be dangerous, as it may silently truncate/reduce some data ! Besides, this behavior is inconsistent and you never know what to expect; until you're faced with he problem. Python 3.0 requires that you specify what you want to, precisely, do !
However, the new string.format() adds some very powerful and useful formatting techniques. It's even very clear with the "free" format '{}'. Like this :
'{}'.format(234)
'{:10}.format(234)
'{:<10}'.format(234)
See ? I didn't need to specify 'integer', 'float' or anything else. This will work for any type of values.
for v in (234, 1.234, 'toto'):
for fmt in ('[{}]', '[{:10}]', '[{:<10d}]', '[{:>10d}]'):
print(fmt.format(v))
Besides, the % value is obsolete and should not be used any more. The new string.format() is easier to use and has more features than the old formatting techniques. Which, IMHO, renders the old technique less attractive.

Python error not enough arguments for format string

Can anyone tell me whats wrong with this:
put(('%s%s.tar.gz' % config.SERVER_PROJECT_PATH, config.RELEASE))
TypeError: not enough arguments for format string
I just want insert two variables in to the string, is my syntax correct?
You need to put the two values in a tuple:
put('%s%s.tar.gz' % (config.SERVER_PROJECT_PATH, config.RELEASE))
otherwise Python sees this as two separate expressions to form a tuple, '%s%s.tar.gz' % config.SERVER_PROJECT_PATH and config.RELEASE.
The syntax is incorrect. The string formatting arguments must be a tuple. You are creating a tuple with the formatted string and the second formatting argument. Use this instead:
put("%s%s.tar.gz" % (config.SERVER_PROJECT_PATH, config.RELEASE))

How to encode a long string of hex values in unicode easily in python

I have hex code point values for a long string. For a short one, following is fine.
msg = unichr(0x062A) + unichr(0x0627) + unichr(0x0628)
print msg
However, since unichr's alternate api unicode() does exist, i thought there must be a way to pass an entire code point string to it. So far i wasn't able to do it.
Now i have to type in a string of 150 hex values (code points) like the 3 above to generate a complete string. I was hoping to get something like
msg = unicode('0x062A, 0x0627....')
I have to use 'msg' latter. Printing it was a mere example. Any ideas?
Perhaps something like this:
", ".join(unichr(u) for u in (0x062A, 0x0627, 0x0628))
Result:
u'\u062a, \u0627, \u0628'
Edit: This uses str.join.
Hard to tell what you're asking for exactly. Are you looking for u'\u062A\u0627\u0628'? The \u escape lets you enter individual characters by code point in a unicode string.
Following your example:
>>> c = u'\u062A\u0627\u0628'
>>> print c
تاب

Categories