Python-string formatting with variable length - python

I'm trying to pad dynamic elements within a table, but it seems as though the native padding function doesn't work with variables. Just wondering if I'm doing something wrong or if there are simple alternatives to center padding. I know of ljust and rjust but there is no m(iddle)just for some reason.
Simple example:
a=10
b='hi'
print(f'{b:^a}')
or
a=10
b='hi'
print('{:^a}'.format(b))
produces
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'a' for object of type 'str'
Typing 10 in place of a in the print statement makes it work as intended, so I'm guessing 'a' is being interpreted as a string by the string formatted. Is a helper function the only way out here?

In [114]: print(f'{b:^{a}}')
hi
In [115]: print(f'"{b:^{a}}"')
" hi "

Probably want to add another set of brackets
a=10
b='hi'
print(f'{b:^{a}}')

Related

Slicing a string from inside a formatted string gives 'TypeError: string indices must be integers'

Shouldn't both these commands do the same thing?
>>> "{0[0:5]}".format("lorem ipsum")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> "{0}".format("lorem ipsum"[0:5])
'lorem'
The commands
>>> "{0[0]}".format("lorem ipsum")
'l'
and
>>> "{0}".format("lorem ipsum"[0])
'l'
evaluate the same. (I know that I can use other methods to do this, I am mainly just curious as to why it dosen't work)
The str.format syntax is handled by the library and supports only a few “expression” syntaxes that are not the same as regular Python syntax. For example,
"{0[foo]}".format(dict(foo=2)) # "2"
works without quotes around the dictionary key. Of course, there are limitations from this simplicity, like not being able to refer to a key with a ] in it, or interpreting a slice, as in your example.
Note that the f-strings mentioned by kendall are handled by the compiler and (fittingly) use (almost) unrestricted expression syntax. They need that power since they lack the obvious alternative of placing those expressions in the argument list to format.

Use Python reserved words in an XML File

I'm currently trying to use python's (3.6) xml.etree.ElementTree commands to write an xml file. Some of the Elements and Subelements I need to write must have "id" and "map" fields, which are reserved python words.
My problem is contained in the following line of code:
ET.SubElement(messages,'trigger',thing='1',bob='a', max='5')
But "max" is a function and I can't use it. Is there a character I can place there to allow me to write this field as I desire? Or some sort of known workaround?
EDIT: I am aware that an '_' stops the python from processing the word, but unfortunately this underscore will show up in my file...so I am trying to see if there is an 'invisible' option for the file I will later be writing.
Thanks much!
Python functions are no problem in the left side of a keyword expression:
>>> def abc(**kwargs):
print kwargs
>>> abc(id=2)
{'id': 2}
>>>
id, map, int, float, str, repr, etc. are built in symbols, not reserved words. You may use them like any other bunch of letters, but assigning it another value replaces the built in symbol:
>>> int(2.5)
2
>>> int = "5"
>>> int(2.5)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
int(2.5)
TypeError: 'str' object is not callable
Notice how the first line is entirely legal, but will trigger a warning if you have a good IDE like pycharm.
If you want to send a actual reserved word to a function, like print, None, yield, or try, you can use the double star ** to convert a dictionary into keyword arguments, for example:
>>> abc(**{"print":2, "None":3})
{'print': 2, 'None': 3}
I hope this answers your question!

Print words using string module and ascii in python?

I was curious about how ASCII worked in python, so I decided to find out more. I learnt quite a bit, before I began to try to print letters using ASCII numbers. I'm not sure if I am doing it correctly, as I am using the string module, but I keep picking up an error
print(string.ascii_lowercase(104))
This should print out "h", as far as I know, but all that happens is that I receive an error.
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
string.ascii_lowercase(104)
TypeError: 'str' object is not callable
If someone could help me solve this, or tell me a better way, I would be ever grateful. Thanks in advance! :)
ascii_lowercase is a string, not a function. Use chr(104).
I guess what you want is chr
>>> chr(104)
'h'
The chr() function returns the corresponding character to the ASCII value you put in.
The ord() function returns the ASCII value of the character you put in.
Example:
chr(104) = 'h'
ord('h') = 104

Printing mixed list in python

I am using Python 3.6. I am using Learn Python the hard way as reference.
I have a mixed list and I am trying to print the elements. The books says to use
format code "r" since we don't know what's in the list. But I am getting error with this.
Was this working in previous versions? How can I print mixed list, each element a time.
Here is my code and error:
change = [1,'pennies',2,'dimes',3,'quarters']
for i in change:
print("I got {:r}".format(i))
Error Stack trace:
Traceback (most recent call last):
File "<pyshell#52>", line 2, in <module>
print("I got {:r}".format(i))
ValueError: Unknown format code 'r' for object of type 'int'
Thanks
For str.format, the "force to repr" conversion is done with !r. not :r; it's not asserting a type for conversion, it's saying "don't use __format__ at all, use __repr__ to perform the conversion". Make it:
print("I got {!r}".format(i))

Get last character of string using `format`

I have to build a path from a given id using this template :
<last digit of id>/<second last digit of id>/<full id>
For instance, if my id is 3412, the expected result would be :
2/1/3412
The id is supposed to have at least 2 digits.
The first thing I tried was:
>>> "{my_id[3]}/{my_id[2]}/{my_id}".format(my_id=str(3412))
'2/1/3412'
But this would work only if the id is 4 digits long.
So what I was expecting to do then was:
>>> "{my_id[-1]}/{my_id[-2]}/{my_id}".format(my_id=str(3412))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
My question here is why can't I use negative indices in my string specifier? And why is Python telling me I'm not using integer indices? I didn't find anything in the documentation about it.
I know there are many other ways to do this, but I'm just curious about why this one does not work.
I'm using python 2.7, but the behaviour seems to be the same under python 3.4.
As vaultah and Bhargav Rao reported in the comments, this is a known issue of python. I'll just have to find an alternative solution!
>>> my_id = str(3412)
>>> "{}/{}/{}".format(my_id[-1], my_id[-2], my_id)
'2/1/3412'

Categories

Resources