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))
Related
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}}')
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.
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
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'
I am trying to use a python script to call an external command a number of times, each time with a different variable.
I see there are recommendations to use subprocess.call to do this, however all the documentation I have found doesn't explain how to pass this function variables (from a list for example).
I have tried a number of different formats, and I think a substitution would be the best, but it seems like the function wont accept the variable.
The code I am trying to get working is:
#!/usr/bin/python
domain_list = ["google.com", "google.ie"]
from subprocess import call
for x in domain_list:
print x
cmd_list = ['dig', '+short', '%s'] %x
call(cmd_list, shell=True)
This is failing with:
Traceback (most recent call last):
File "./dnscheck.py", line 16, in <module>
cmd_list = ['dig', '+short', '%s'] %arg
TypeError: unsupported operand type(s) for %: 'list' and 'str'
Really I want to be able to pass a bunch of different domains (defined in a list) to dig and receive the IP's of those domains.
I've just started with python so sorry if this is very basic!
You are trying to use the modulo operator on a list, I presume you wanted to do string formatting on the last item, as the percentage symbol is overloaded to do formatting with strings, but as you just want to insert the item without any formatting, you can just give it directly:
['dig', '+short', x]
If you did want to use formatting, you would need to do it on the string:
['dig', '+short', '%s' % x]
Note however, that this is pointless given you are not doing any formatting.