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'
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}}')
I want to capture data and numbers from a string in python. The string is a measurement from an RF sensor so it might be corrupted from bad transmission. Strings from the sensor look like this PA1015.7 TMPA20.53 HUM76.83.
My re is :
s= re.search('^(\D+)([0-9.]+'),message)
Now before I proceed I want to check if I truly received exactly two matches properly or if the string is garbled.
So I tried :
len(s)
But that errors out :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type '_sre.SRE_Match' has no len()
I do need access to the match group elements for processing later. (I think that eliminates findall)
key= s.group(1)
data= s.group(2)
What's missing?
Instead of using search, you should use findall instead:
s = re.findall('(\D+)([0-9.]+)',message)
print("matched " + str(len(s)))
search only returns whether there is or is no match in the input string, in the form of a boolean.
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.
## A little helper program that capitalizes the first letter of a word
def Cap (s):
s = s.upper()[0]+s[1:]
return s
Giving me this error :
Traceback (most recent call last):
File "\\prov-dc\students\jadewusi\crack2.py", line 447, in <module>
sys.exit(main(sys.argv[1:]))
File "\\prov-dc\students\jadewusi\crack2.py", line 398, in main
foundit = search_method_3("passwords.txt")
File "\\prov-dc\students\jadewusi\crack2.py", line 253, in search_method_3
ourguess_pass = Cap(ourguess_pass)
File "\\prov-dc\students\jadewusi\crack2.py", line 206, in Cap
s = s.upper()[0]+s[1:]
IndexError: string index out of range
As others have already noted, the problem is that you're trying to access an item in an empty string. Instead of adding special handling in your implementation, you can simply use capitalize:
'hello'.capitalize()
=> 'Hello'
''.capitalize()
=> ''
It blows up, presumably, because there is no indexing an empty string.
>>> ''[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
And as it has been pointed out, splitting a string to call str.upper() on a single letter can be supplanted by str.capitalize().
Additionally, if you should regularly encounter a situation where this would be passed an empty string, you can handle it a couple of ways:
…#whatever previous code comes before your function
if my_string:
Cap(my_string) #or str.capitalize, or…
if my_string being more or less like if len(my_string) > 0.
And there's always ye old try/except, though I think you'll want to consider ye olde refactor first:
#your previous code, leading us to here…
try:
Cap(my_string)
except IndexError:
pass
I wouldn't stay married to indexing a string to call str.upper() on a single character, but you may have a unique set of reasons for doing so. All things being equal, though, str.capitalize() performs the same function.
>>> s = 'macGregor'
>>> s.capitalize()
'Macgregor'
>>> s[:1].upper() + s[1:]
'MacGregor'
>>> s = ''
>>> s[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[:1].upper() + s[1:]
''
Why does s[1:] not bail on an empty string?
Tutorial on strings says:
Degenerate slice indices are handled gracefully: an index that is too
large is replaced by the string size, an upper bound smaller than the
lower bound returns an empty string.
See also Python's slice notation.
I just had the same error while I was sure that my string wasn't empty. So I thought I'd share this here, so people who get that error have as many potentional reasons as possible.
In my case, I declared a one character string, and python apparently saw it as a char type. It worked when I added another character. I don't know why it doesn't convert it automatically, but this might be a reason that causes an "IndexError: string index out of range", even if you think that the supposed string is not empty.
It might differ between Python versions, I see the original question refers to Python 3. I used Python 2.6 when this happened.
Python 2.7.3
>>> print '%2.2f' % 0.1
0.10
The documentation I have says that type % should be the same as type f except that the input is multiplied by 100.
>>> print '%2.2%' % 0.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
use the new format expression, which has the formatter you are referring to
print "{:%}".format(0.1)
#10.000000%
if you just want the integer part you can use the precision specification
print "{:.0%}".format(0.1)
#10%
see the doc at
http://docs.python.org/2/library/string#formatspec
To expand a little bit, the new format specificator is really more powerful than the old one. First of all it's really simple calling the parameters by order or name
"play the {instrument} all {moment}, even if my {instrument} is old".format(moment='day', instrument='guitar')
#'play the guitar all day, even if my guitar is old'
then, as can be seen in the documentation, is possible to have access to properties of the object:
"the real component is {0.real} and the imaginary one is {0.imag}".format(3+4j)
#'the real component is 3.0 and the imaginary one is 4.0'
There is a lot more than this, but you can find it all in the documentation, that is very clear.
Came across this question. In Python 3 you can simply use fstrings (thus avoiding the .format) in a similar way as described above. The format is:
print(f"{your_number:.n_decimals%}")
Eg.
>>> print(f"{0.0350:.2%}")
3.50%
print '%2.2%' % 0.1
Tells it that there are 2 placeholders in format string (%), so you have a complain