2,646 Posted Topics

Member Avatar for keitaurin

You can use the `re` module >>> import re >>> string = "hello world!" >>> result = re.sub(r'\s+', ' ', string) >>> print(result) hello world! Another way is to split and join >>> result = ' '.join(string.split()) >>> print(result) hello world!

Member Avatar for Lardmeister
0
185
Member Avatar for OmK@r
Member Avatar for mksha

Don't catch an exception only to raise a new one unless you know what you are doing! It hides the original exception and prevents debugging. So you could replace line 24 above with a naked `raise` statement to see where the error occured. You can use the Command class from …

Member Avatar for mksha
0
469
Member Avatar for krystosan

Always post the traceback when you report such errors! If it is a SyntaxError, use `print("module {0}".format(key))`. Otherwise, the format() method could cause an error in some cases (unicode encoding, or use of a custom class).

Member Avatar for vegaseat
0
344
Member Avatar for syfr

You could probably use a non blocking input with a call to select() like in this example (linux only): #!/usr/bin/env python # -*-coding: utf8-*- from __future__ import unicode_literals, print_function, division __doc__ = """ module: sandbox.pollinput - """ import select import sys import time def opt_input(): i, w, x = select.select([sys.stdin], …

Member Avatar for Gribouillis
0
960
Member Avatar for lancevo3

Well, it looks like class A(object): # <--- small 'c' def __init__(self): self.a = 4 # <--- a and b are instance variables (not class variables) self.b = 6 class B(A): def __init__(self): # <--- watch the number of underscores A.__init__(self) # <--- call parent class constructor explicitely #some code …

Member Avatar for Ene Uran
0
1K
Member Avatar for flebber
Member Avatar for Jacklittle01
Member Avatar for Gribouillis

This snippet defines a Print function which can be used with python 2.4, 2.5, 2.6 and 3.0 (for 3.0 this is just the built-in print function). It's interface is that of the python 3.0's print. It simplifies the task of writing transitional code which runs under python 2.5 and python …

Member Avatar for Lucaci Andrew
1
818
Member Avatar for clouds_n_things
Member Avatar for clouds_n_things
0
234
Member Avatar for bumsfeld

[QUOTE=ajipw;1193849]i'm a student and i want to create an electronic dictionary, can you help me?[/QUOTE] You should start your own thread instead of reviving an old one, and also tell us what you mean by 'create an electronic dictionary', which is not exactly the same thing as a python dictionary.

Member Avatar for Umar Suleman
3
410
Member Avatar for TrustyTony

The interpreter only obeys python's grammar which says that both sides of a comparison operator must be "or_expr"s (one of python's syntactic categories). An expression like `not ...` can not be considered an or_expr. With parenthesis, it becomes an "atom", which can be considered as an "or_expr". Grammar is a …

Member Avatar for ZZucker
2
188
Member Avatar for Rod53718

The best solution to avoid circular imports. If A imports B, then B should not import A, or import from A (although python is very permissive and will tolerate almost everything). Here, main imports submodule and both use printa(). You can write printa() and num_values in a third module, and …

Member Avatar for Rod53718
0
270
Member Avatar for sudipta.mml
Member Avatar for sudipta.mml
0
525
Member Avatar for dashing.adamhughes

The first way is to define `__getattr__()` class Bar(object): def __getattr__(self, attr): return getattr(self.foo, attr) You can add some conditions on attr to avoid unexpected calls class Bar(object): def __getattr__(self, attr): if some_condition(attr): return getattr(self.foo, attr) else: raise AttributeError(attr) Another way is to define methods by a loop, eg class …

Member Avatar for dashing.adamhughes
0
359
Member Avatar for pars99

At line 8, python thinks that a variable `left` is used, which was not previously defined. You probably meant if partone == 'left': Here `'left'` is a constant string instead of a variable name.

Member Avatar for vegaseat
0
279
Member Avatar for chao.lee.927

In wxpython, it's 4 lines of code mg =wx.lib.gestures.MouseGestures (our_panel, True , wx.MOUSE_BTN_LEFT) mg .SetGesturePen(wx.Colour(255 ,0 ,0 ), 2) mg .SetGesturesVisible(True) mg .AddGesture ('DR', our_method) I don't know the PyQT equivalent.

Member Avatar for Gribouillis
0
203
Member Avatar for biscayne

The solution is to use lists loc = locals() pf_list = [loc["p%sf" % x] + float(loc["p%s" % x]) for x in "abcdefgh"] ps_list = ["%.2f" % val for val in pf_list] or dicts loc = locals() pf_dict= dict((x, loc["p%sf" % x] + float(loc["p%s" % x])) for x in "abcdefgh") ps_dict …

Member Avatar for biscayne
0
250
Member Avatar for krystosan

`os.getenv('PATH')` is the sequence of folders where the operating system finds executable programs. `sys.path` is the sequence of folders where python finds importable modules.

Member Avatar for krystosan
0
1K
Member Avatar for neely615

Use the format method #!/usr/bin/env python # -*-coding: utf8-*- from __future__ import unicode_literals, print_function, division template = str("""<Result Type="PkFilter" Name="{RowNum:0>2d}" Color="{Color}" Show="0" MinIntensity="0" IntensityThreshold="100" AbsIntens="0" LogScale="0" MinMass="{MinMass}" MaxMass="{MaxMass}" Integrate="1" UsePercentile="0" IntensityPercentile="0.95" FindMass="0" RelMass="1"></Result>""").replace("\n", " ") def result(RowNum, MinMass, MaxMass, Color=str("#0000ff")): return template.format( RowNum = int(RowNum), MinMass = repr(float(MinMass)), # repr …

Member Avatar for neely615
0
173
Member Avatar for LinaClark

There is something strange in this code >>> 'easyhint' < 8 False You are comparing constant strings to integers. You probably meant something else. This needs to be corrected.

Member Avatar for Gribouillis
0
233
Member Avatar for dilbert_here00

You could use an xmlrpc server on the remote computer. See the standard library module xmlrpclib.

Member Avatar for Gribouillis
0
470
Member Avatar for Jacklittle01
Member Avatar for james.lu.75491856
0
187
Member Avatar for felix001

There is no *best way*, there are different ways >>> class A(object): ... def __init__(self): ... self.mydict = dict() # <-- a dict is added to every instance ... >>> a = A() >>> a.mydict["foo"] = "bar" >>> >>> class B(object): ... shareddict = dict() # <-- this dict can …

Member Avatar for vegaseat
0
124
Member Avatar for james.lu.75491856

Your tuple contains probably a list >>> D = dict() >>> t = ([0], 1) >>> D[t] = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

Member Avatar for james.lu.75491856
0
588
Member Avatar for krystosan

If it is a csv file, it would be easier to read with the csv module. You would select the first entry of each row to get the first name. Can you post a few rows of your file (with real names and addresses replaced by similar fancy data) ?

Member Avatar for snippsat
0
406
Member Avatar for Gribouillis

This small python script invokes the [Treeline](http://treeline.bellz.org/index.html) tree visualizer to display xml files in a pleasant way. ![viewxml](/attachments/large/1/viewxml.png "viewxml")

0
2K
Member Avatar for PhilEaton

I'm not (yet) a specialist of web frameworks in python, but yes, one of the purposes of templating systems is to mix html code and python code. The main idea is to write html files containing python expressions and blocks of code with a special markup syntax. This file is …

Member Avatar for Gribouillis
0
243
Member Avatar for pbnoj

You could insert 0.0 when there is no data Resistance.append(tuple((float(x) if x.strip() else 0.0) for x in row[4:]))

Member Avatar for Gribouillis
0
4K
Member Avatar for aaaaaaaaa

Add a function to filter users def _my_users(users): for user in users: try: if not all(cg == "default" for cg in users[user]["group"]): yield user except KeyError: pass my_users = list(_my_users(users)) for user in my_users: # ... etc

Member Avatar for Gribouillis
0
371
Member Avatar for RLS0812
Member Avatar for TrustyTony
0
235
Member Avatar for tirexxerit

If `n` is an integer, `n << 8` is equivalent to `n * (2**8)`. The `<<` operator is called the left shift operator. It comes from the binary representation of integers, for example 6 is represented as `110` in binary form, and `6 << 3` as `110000`. Other languages use …

Member Avatar for tirexxerit
0
197
Member Avatar for ihatehippies

You don't really need to be fluent in C++, the program contains only a few function calls which you can find in the [pywin32 API](http://timgolden.me.uk/pywin32-docs/PyWin32.html), especially [here](http://timgolden.me.uk/pywin32-docs/win32file.html). I won't do it for you because the intricacies of windows are not particularly my cup of tea (I'm a linux geek). Also …

Member Avatar for Gribouillis
0
265
Member Avatar for jkembo

Which cells do you you want to merge ? what is their content ? What should the merged cell contain ?

Member Avatar for jkembo
0
13K
Member Avatar for SoulMazer
Member Avatar for Gribouillis
1
738
Member Avatar for Jezza25
Member Avatar for runlevel3nut

You can remove lines 6 to 11 because `raw_input()` always return a `str` object. The string's content is not examined, if the user types `123`, the string `"123"` is returned. `.isalpha()` tests if _all_ the characters in the string are alphabetic, for example `"ps2pdf".isalpha()` returns `False`. Otherwise, *variable* is not …

Member Avatar for runlevel3nut
0
248
Member Avatar for slasel

Read [this](http://effbot.org/tkinterbook/label.htm) and also [this](http://lmgtfy.com/?q=tkinter+label+widget)

Member Avatar for Lardmeister
0
109
Member Avatar for krystosan

You can chek that the parent directory exists import os def is_probably_valid(thepath): head, tail = os.path.split(thepath) return os.path.isdir(head) The ultimate test is to create a file with this path (if it does not already exist). File creation may fail depending on the user's or folder's permission for example.

Member Avatar for Gribouillis
0
129
Member Avatar for Gribouillis

This snippet is easy: it defines an immutable wrapper around a sequence type (list, deque, etc) which allows a class, function or module to expose a read only version of a sequence to the outer world. A constant wrapper around mapping types could also be defined in a similar manner.

Member Avatar for Gribouillis
2
578
Member Avatar for biscayne

You can use a boolean flag for elem in lstLine[1:]: with open(fname) as ifh: found = False for item in ifh: lstData = item.rstrip('\n').split(';') andexfield = lstData[0] if andexfield == elem: found = True do bladibla if not found: print(...)

Member Avatar for Gribouillis
0
278
Member Avatar for satsujin

Here is a code that works for me from Tkinter import * class App(object): def __init__(self, width=256, height=256): self.width = width self.height = height self.root = Tk() self.root.title("tkinter_test01") self.root.geometry("%sx%s"%(self.width, self.height)) self.canvas = Canvas(self.root, width=self.width, height=self.height) self.canvas.pack() self.views = [win1(self.canvas), win2(self.canvas)] self.view_idx = 0 self.canvas.bind("<Button-1>", self.switch_view) self.current_view.repaint_canvas() def switch_view(self, event): self.view_idx …

Member Avatar for satsujin
0
190
Member Avatar for krystosan

`pickle.loads()` works very well unless the pickle was written with a different version of python. What you can do is check the integrity of your data by sending the data together with an md5 or sha sum (see module `hashlib`). Your remote process must compute the checksum of the pickled …

Member Avatar for Gribouillis
0
749
Member Avatar for giancan

I have formulas, if `(x0, y0)` and `(x1, y1)` are two points on the track. The line joining them has the equation (y1-y0) * x - (x1-x0) * y = x0 * y1 - x1 * y0 The parallel line on the right at a distance `r` has the equation …

Member Avatar for giancan
0
401
Member Avatar for Cosmo_Kramer

searchMaze() creates a path_so_far which is a list containing a single element (start_pos), then it calls searchMazeRecurse() if start_pos is different from finish_pos. hey! this is my 3000th post ! let's clink glasses.

Member Avatar for Cosmo_Kramer
0
277
Member Avatar for slasel
Member Avatar for slasel
0
590
Member Avatar for elbert.leach

Take a page containing a list of sentences, like [this one](http://ufal.mff.cuni.cz/~toman/pedt_manual/ar01.html) (take only the first 5 sentences). Then with a calculator, compute the average number of words per sentence by hand and note carefully everything you do. This should give you a working algorithm. Write pseudo code, then python code.

Member Avatar for Ene Uran
0
341
Member Avatar for slasel

Perhaps use the `after()` method like in [this example](http://www.daniweb.com/software-development/python/code/216785/tkinter-digital-clock-python).

Member Avatar for Ene Uran
0
436
Member Avatar for krystosan

The first thing to do is to avoid `import *`. Import only specific names. What you could do in this case is a function # file RenderUI.py def main(): app = QtGui.QApplication(sys.argv) app.setStyle("cleanlooks") win = Window() win.show() sys.exit(app.exec_()) and in the other file # file Render.py from RenderUI import main …

Member Avatar for krystosan
0
961
Member Avatar for giancan

You can use a namedtuple as a simple container from collections import namedtuple FileInfo = namedtuple("FileInfo", "path foo bar baz") mylist=[] for file in glob.glob(inputpath+"\\*.txt"): mylist.append(FileInfo(file, value1, value2, value3)) import pickle pkl = "fileinfo.pkl" with open(pkl, "wb") as ofh: pickle.dump(mylist, ofh) with open(pkl, "rb") as ifh: print(pickle.load(ifh))

Member Avatar for ZZucker
0
325

The End.