What am I doing wrong to get this error?
replacements = {}
replacements["**"] = ("<strong>", "</strong>")
replacements["__"] = ("<em>", "</em>")
replacements["--"] = ("<blink>", "</blink>")
replacements["=="] = ("<marquee>", "</marquee>")
replacements["##"] = ("<code>", "</code>")
for delimiter, (open_tag, close_tag) in replacements: # error here
message = self.replaceFormatting(delimiter, message, open_tag, close_tag);
The error:
Traceback (most recent call last):
File "", line 1, in
for doot, (a, b) in replacements: ValueError: need more than 1 value to
unpack
All the values tuples have two values. Right?
It should be:
for delimiter, (open_tag, close_tag) in replacements.iteritems(): # or .items() in py3k
I think you need to call .items() like the third example in this link
for delimiter, (open_tag, close_tag) in replacements.items(): # error here
message = self.replaceFormatting(delimiter, message, open_tag, close_tag)
Related
So, my interpereter is complaining about IndexError: Replacement index 1 out of range for positional args tuple when calling re.group(#) or re.groups() under specific circumstances. It is meant to return a phone number, such as +1 (555) 555-5555
Here is the regex used, as it is declared elsewhere:
self.phoneRegex = re.compile(r'(\+\d) (\(\d\d\d\)) (\d\d\d)(\d\d\d\d)')
Here is the code causing the issues:
for cell in self.cells:
if '+1' in cell.text:
print(self.pmo.groups()) #Works fine
print("{} {} {}-{}".format(self.pmo.groups())) #Errors out.
print("{} {} {}-{}".format(self.pmo.group(1), self.pmo.group(2),self.pmo.group(3), self.pmo.group(4))) #Also errors out.
if isinstance(self.cursor(row=self.data['lst_row'], column=self.telCol).value, type(None)):
self.cursor(row=self.data['lst_row'], column=self.telCol).value = "{} {};".format("{} {} {}-{}".format(self.pmo.group(2), self.pmo.group(2),self.pmo.group(3), self.pmo.group(4)))
Full Traceback:
Traceback (most recent call last):
File "F:\Documents\Programs\Python\E45 Contact Info Puller\main.py", line 289, in run
print("{} {} {}-{}".format(self.pmo.groups()))
IndexError: Replacement index 1 out of range for positional args tuple
You have this string.format line:
print("{} {} {}-{}".format(self.pmo.groups()))
re match groups are tuples, so here, you have 4 format substitutions, but you're trying to pass a single tuple (that contains 4 matches per your regex) instead of 4 separate argument for formatting.
You need to unpack (or splat) the tuple for the string formatting - notice the * added before self.pmo.groups().
print("{} {} {}-{}".format(*self.pmo.groups()))
I am trying to execute a python script which is giving me an IndexError. I understood that the rsplit() method failed to split the string. I don't exactly know why it is showing index out of range. Could anyone tell me how to solve this problem ?
code
raw_directory = 'results/'
for name in glob.glob(raw_directory + '*.x*'):
try:
#with open(name) as g:
# pass
print(name)
reaction_mechanism = 'gri30.xml' #'mech.cti'
gas = ct.Solution(reaction_mechanism)
f = ct.CounterflowDiffusionFlame(gas, width=1.)
name_only = name.rsplit('\\',1)[1] #delete directory in filename
file_name = name_only
f.restore(filename=raw_directory + file_name, name='diff1D', loglevel=0)
Output
If I delete the file strain_loop_07.xml, I got the same error with another file.
results/strain_loop_07.xml
Traceback (most recent call last):
File "code.py", line 38, in <module>
name_only = name.rsplit('\\'1)[1] #delete directory in filename
IndexError: list index out of range
If rsplit failed to split the string, it returns an array with only one solution, so the [0] and not [1]
I understood in reply of this post that "name" variable is filled with text like "result/strain_loop_07.xml", so you want to rsplit that, with a line more like
name_only = name.rsplit('/', 1)[1]
So you'll get the "strain_loop_07.xml" element, which is what you probably wanted, because name.resplit('/', 1) return something like
['result', 'strain_loop_07.xml']
By the way, don't hesitate to print your variable midway for debuging, that is often the thing to do, to understand the state of your variable at a specific timing. Here right before your split !
Sorry if this is a dumb question but I am having a few issues with my code.
I have a Python script that scrapes Reddit and sets the top picture as my desktop background.
I want it to only download if the picture is big enough, but I am getting a strange error.
>>> m = '1080x608'
>>> w = m.rsplit('x', 1)[0]
>>> print(w)
1080
>>> h = m.rsplit('x', 1)[1]
>>> print(h)
608
This works fine, but the following doesn't, despite being almost the same.
>>> m = '1280×721'
>>> w = m.rsplit('x', 1)[0]
>>> h = m.rsplit('x', 1)[1]
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
h = m.rsplit('x', 1)[1]
IndexError: list index out of range
In your second example × is not the same as x, it is instead a multiplication sign. If you are getting these stings from somewhere and then parsing them, you should first do
m = m.replace('×', 'x')
× != x. Split returns one-element list, and you are trying to retrieve second element from it.
'1080x608'.rsplit('x', 1) # ['1080', '608']
'1280×721'.rsplit('x', 1) # ['1280\xc3\x97721']
In second case there is no second element in list - it contains only one element.
MCVE would be:
l = ['something']
l[1]
With exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
To ensure that you split string to two parts you may use a partition.
Split the string at the first occurrence of sep, and return a 3-tuple
containing the part before the separator, the separator itself, and
the part after the separator. If the separator is not found, return a
3-tuple containing the string itself, followed by two empty strings.
w, sep, h = m.partition('x')
# h and sep will be empty if there is no separator in m
I have a string like that: 'aaa(cc(kkk)c)ddd[lll]{m(aa)mm}'. From that string I want to get the following structure: ['aaa', '(cc(kkk)c)', 'ddd', '[lll]', '{m(aa)mm}']. In other words I would like to separate substrings that are in brackets of different types.
You need to use a stack approach to track nesting levels:
pairs = {'{': '}', '[': ']', '(': ')'}
def parse_groups(string):
stack = []
last = 0
for i, c in enumerate(string):
if c in pairs:
# push onto the stack when we find an opener
if not stack and last < i:
# yield anything *not* grouped
yield string[last:i]
stack.append((c, i))
elif c in pairs:
if stack and pairs[stack[-1][0]] == c:
# Found a closing bracket, pop the stack
start = stack.pop()[1]
if not stack:
# Group fully closed, yield
yield string[start:i + 1]
last = i + 1
else:
raise ValueError('Missing opening parethesis')
if stack:
raise ValueError('Missing closing parethesis')
if last < len(string):
# yield the tail
yield string[last:]
This will generate groups, cast to a list if you need one:
>>> list(parse_groups('aaa(cc(kkk)c)ddd[lll]{m(aa)mm}'))
['aaa', '(cc(kkk)c)', 'ddd', '[lll]', '{m(aa)mm}']
If the brackets / parenthesis do not balance, an exception is raised:
>>> list(parse_groups('aa(bb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 19, in parse_groups
ValueError: Missing closing parethesis
>>> list(parse_groups('aa[{bb}}'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 20, in parse_groups
ValueError: Missing opening parethesis
>>> list(parse_groups('aa)bb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 20, in parse_groups
ValueError: Missing opening parethesis
You could also look at pyparsing. Interestingly, this can be implemented as a stack, where you can push string fragments when you find {[( and pop when you find )]}.
I think you could try Custom String Parser library (I'm the author of it). It's designed to work with data which has any logical structure, so you can customize it the way you want ;)
How does string.join resolve? I tried using it as below:
import string
list_of_str = ['a','b','c']
string.join(list_of_str.append('d'))
But got this error instead (exactly the same error in 2.7.2):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/string.py", line 318, in join
return sep.join(words)
TypeError
The append does happen, as you can see if you try to join list_of_string again:
print string.join(list_of_string)
-->'a b c d'
here's the code from string.py (couldn't find the code for the builtin str.join() for sep):
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words)
What's going on here? Is this a bug? If it's expected behavior, how does it resolve/why does it happen? I feel like I'm either about to learn something interesting about the order in which python executes its functions/methods OR I've just hit a historical quirk of Python.
Sidenote: of course it works to just do the append beforehand:
list_of_string.append('d')
print string.join(list_of_string)
-->'a b c d'
list_of_str.append('d')
does not return the new list_of_str.
The method append has no return value and so returns None.
To make it work you can do this:
>>> import string
>>> list_of_str = ['a','b','c']
>>> string.join(list_of_str + ['d'])
Although that is not very Pythonic and there is no need to import string... this way is better:
>>> list_of_str = ['a','b','c']
>>> ''.join(list_of_str + ['d'])