2,646 Posted Topics

Member Avatar for TrustyTony
Member Avatar for Skyelher

There is no reason to avoid it, it's a standard construct in python which means 'repeat indefinitely'. You can use [icode]while True:[/icode] which is semantically better, but it doesn't change much.

Member Avatar for griswolf
0
150
Member Avatar for cableguy31

re.search returns a 'match object' or None. Follow this example [code=python] >>> mo = re.search(r"b\w+", "'Give me bacon and eggs,' said the other man.") >>> mo <_sre.SRE_Match object at 0x7f90947e2e68> >>> mo.group(0) 'bacon' [/code]

Member Avatar for cableguy31
0
84
Member Avatar for SoulMazer
Member Avatar for SoulMazer
0
111
Member Avatar for debragail

If f is a fraction, you can use f.denominator and f.numerator. See also this snippet [url]http://www.daniweb.com/code/snippet223956.html[/url].

Member Avatar for debragail
0
183
Member Avatar for muthukumarangms

If you only have the .pyc files (and not the .py files), the best solution is to install a version of python 2.5 on your system and run the installer with this version of python. You can have several versions of python on the same system (I currently use 2.5, …

Member Avatar for muthukumarangms
0
3K
Member Avatar for cadtel

The problem is that you convert [b]twice[/b] the angles to degrees. For example the part [icode]if type == "SSS"[/icode] should look like [code=python] if type=="SSS": print("\nYou picked SSS. Type in each number, seperated by a space\n") nums=input("Numbers:\t").split() nums=[float(eval(i)) for i in nums] resultdict=SSS(nums[0],nums[1],nums[2]) # LINE SUPPRESSED print("\nsides:\t ", resultdict["sides"], " …

Member Avatar for TrustyTony
0
194
Member Avatar for Tommymac501

You should probably write [code=python] print usps4s.USPS_4State('1234987654321', '01234567891').barcodes [/code] or [code=python] from usps4s import USPS_4State print USPS_4State('1234987654321', '01234567891').barcodes [/code]

Member Avatar for Tommymac501
0
111
Member Avatar for chavanak

First when you iterate over the lines, there is a newline character at the end of each line. This newline can be removed with [icode]line = line.rstrip("\r\n")[/icode]. You should write this as the first statement in the for loop. Then I suggest that you invoke an output function instead of …

Member Avatar for Beat_Slayer
0
1K
Member Avatar for foco
Member Avatar for jagan605
0
88
Member Avatar for happymadman

I managed adding an element this way [code=python] from lxml import etree from lxml.builder import ElementMaker E = ElementMaker() DOC = E.doc PERSON = E.activity TITLE = E.title DESC = E.desc IDNO = E.idno def NAME(*args): return {"name":' '.join(args)} file = "xmltestthing.xml" parser = etree.XMLParser(remove_blank_text=True) # see http://codespeak.net/lxml/FAQ.html#parsing-and-serialisation thing1 = …

Member Avatar for happymadman
0
229
Member Avatar for G_S

Unfortunately, the os.startfile function exists only in Windows. A multiplatform way is [code=python] import subprocess as sp sp.call(["python", "textversion.py"]) [/code] Or, even better [code=python] import subprocess as sp import sys returncode = sp.call([sys.executable, "textversion.py"]) [/code]

Member Avatar for G_S
0
376
Member Avatar for masterofpuppets

Also note [code=python] >>> bin(45) # python >= 3.0 '0b101101' >>> int('1110', 2) # python >= 2.5 14 [/code] Finally, see also [url=http://code.activestate.com/recipes/440528/]this link[/url].

Member Avatar for TrustyTony
0
798
Member Avatar for G_S

[QUOTE=G_S;1242407]Hi, I'm trying to make a frontend for the compile module in python. Everything works just right, except when the file has mistakes in the code that lead to a syntax error. It does raise the invalid syntax error in the terminal, but instead of executing the block inside the …

Member Avatar for G_S
0
2K
Member Avatar for andrewtrench

Well, here is an example [code=python] class Thingy(object): instances = [] def __init__(self): self.instances.append(self) def waste_time_and_memory(): t = Thingy() for i in range(5): waste_time_and_memory() print Thingy.instances """ My output --> [<__main__.Thingy object at 0x7f0581777c50>, <__main__.Thingy object at 0x7f0581777c90>, <__main__.Thingy object at 0x7f0581777cd0>, <__main__.Thingy object at 0x7f0581777d10>, <__main__.Thingy object at 0x7f0581777d50>] …

Member Avatar for andrewtrench
0
9K
Member Avatar for vegaseat

I just tested it with python 2.6 and it works. For python 3.1, I had to change the last statement to [code=python] print(int2roman(int(input("Enter an integer (1 to 4999): ")))) [/code] and it works.

Member Avatar for eljakim
0
3K
Member Avatar for Purnima12

I think you should not start with a complicated gui interface. You could use simple tables like in this google code project [url]http://code.google.com/p/prettytable/[/url] to display the monthly schedule (it can generate html to view the table in your browser too). With this simple output, concentrate on the math of the …

Member Avatar for Purnima12
0
2K
Member Avatar for WildBamaBoy

To test if a path is a file, you can use [code=python] import os os.path.isfile(path) # is it a file ? os.path.isdir(path) # is it a folder ? os.path.exists(path) # does it exist in the file system ? [/code]

Member Avatar for WildBamaBoy
0
142
Member Avatar for Valchris

Since the server crashed, it displayed the exception, probably a socket.error, so use [icode]except socket.error[/icode]. In except block, put the code that you want to execute when the client disconnects in an unexpected way (it could be a simple pass statement). Also, if these lines are in a loop which …

Member Avatar for Gribouillis
0
96
Member Avatar for G_S

Perhaps you should write this at the top of your file [code=text] <?xml version="1.0" encoding="UTF-8"?> [/code]

Member Avatar for Gribouillis
0
187
Member Avatar for ErlendHL

Because the syntax [code=python] p = [ expression ] * 3 [/code] evaluates the expression once and creates a list of 3 references to the result of this evaluation. You can use [code=python] p = [ expression for i in range(3) ] [/code] to evaluate the expression thrice and put …

Member Avatar for ErlendHL
0
94
Member Avatar for leiger

The command python alone starts an interactive interpreter in a console. You should try sendToConsole("python FILENAME.py") which executes a python program and don't enter interactive mode.

Member Avatar for Gribouillis
0
648
Member Avatar for alphaOri

The strange thing is not python's behavior, but your idea of initializing a base class object using the __init__ method of a subclass. The purpose of __init__ methods is to build an object, and therefore, the __init__ method of class child2 should be used to create a child2 instance. Usually …

Member Avatar for alphaOri
0
151
Member Avatar for prashanth s j

I once wrote a small code snippet that does this and more: [url]http://www.daniweb.com/code/snippet257449.html[/url]

Member Avatar for prashanth s j
0
207
Member Avatar for lstensland

Perhaps you could read the sticky thread Starting Python [url]http://www.daniweb.com/forums/thread20774.html[/url] !

Member Avatar for lstensland
0
443
Member Avatar for daanh

Apparently, it comes from a function in a file named formatting.py in xlrd source, wihch tests wether a string is a date formatting string. I think you should ignore the warning.

Member Avatar for Gribouillis
0
134
Member Avatar for Syphilis

This line [icode]server_socket.bind(("0.0.0.0", 5000))[/icode] looks suspicious. Normally, the address of localhost is 127.0.0.1. You should try with this address.

Member Avatar for Syphilis
0
141
Member Avatar for pixeldroid

An more common alternative is [code=python] >>> L = ['cmds.sphere(n = "aBall", r = 1)', 'cmds.sphere(n = "aBall", r = 2)', 'cmds.sphere(n = "aBall", r = 3)', 'cmds.sphere(n = "aBall", r = 4)', 'cmds.sphere(n = "aBall", r = 5)', 'cmds.sphere(n = "aBall", r = 6)'] >>> import cPickle as Pickle …

Member Avatar for pixeldroid
0
175
Member Avatar for Pinchanzee

If you are in a hurry to run your code, start idle, File --> New Window opens an editor window. Enter a few lines of python, then hit the F5 key : your code is running !

Member Avatar for Pinchanzee
0
96
Member Avatar for G_S

[QUOTE=G_S;1234813]Oh, wait, it's not completely solved: on linux, everything is fine. on windows, however, webbrowser.open only opens Explorer, even though firefox is the default. If I try startfile, it does open the associated program as d5e5 explained, but it fails to open the help file (it seems it only works …

Member Avatar for G_S
0
4K
Member Avatar for TrustyTony

[QUOTE=tonyjv;1238985] [B]Point one[/B] You can do comparison with tuples of numbers in Python [CODE]>>> (0,0)<(1,1)<(2,2) True >>> (0,0)<(1,1)<(2,0) True >>> [/CODE] First is fine for me, but I am not agreeing with the second one. Why? If a<b<c, then number b is between a and c in the number line. …

Member Avatar for TrustyTony
0
338
Member Avatar for ryan461

If you only want to catch the exception and let your code still run, you only need to write [code=python] import socket def email(): global mssg session = smtplib.SMTP(smtpserver) if authrequired: session.login(smtpuser, smtpass) try: session.sendmail(SENDER, RECIPIENTS, mssg) session.quit() except socket.error: logit('server down') [/code] Don't write [icode]except:[/icode] statements without targeting at …

Member Avatar for ryan461
0
381
Member Avatar for lsmurfl

Did you learn how to write a function ? Then start writing a function to generate a single random birthday [code=python] import random def generate_birthday(): # PUT YOUR EFFORTS HERE ????? return birthday print(generate_birthday()) [/code]

Member Avatar for vegaseat
0
108
Member Avatar for larsen182

As a starting point, here is a function which computes the averages for a sequence of values (parameter A, parameter B, time). The assumption is that the input data are sorted by time. Try to run it and see if it does what you want [code=python] from itertools import groupby …

Member Avatar for larsen182
0
219
Member Avatar for cyon

I would use something like [code=python] from collections import defaultdict def list_has_duplicate_items(L): return len(L) > len(set(L)) def get_duplicate_items(L): D = defaultdict(int) for k in L: D[k] += 1 return [k for (k, v) in D.items() if v > 1] [/code]

Member Avatar for TrustyTony
0
2K
Member Avatar for vlady

I suggest to add a random number in the tuples being sorted [code=python] from random import random def test(words): t = [] for word in words: t.append((len(word), random(), word)) t.sort(reverse=True) res = [] for length, rand, word in t: res.append(word) print res test(['hello','my','friend','Peter']) [/code]

Member Avatar for vlady
0
147
Member Avatar for sarosh

Also, if you want to exit from a deeply nested point during the execution you can use [code=python] raise SystemExit [/code] or [code=python] import sys sys.exit(0) # use another value, like -1 to mean program failure [/code]

Member Avatar for vegaseat
0
128
Member Avatar for qqabb

The list class 'index' method performs a linear search [code=python] >>> mylist = list("hello world") >>> print(mylist) ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> mylist.index('w') 6 >>> mylist[6] 'w' >>> mylist.index('z') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.index(x): …

Member Avatar for TrustyTony
0
1K
Member Avatar for shwick

Here is a version which builds a single regex for all the sentences. You can add as many sentences as you whish, as long as they contain a single occurence of <mob> [code=python] # tested with python 2.6 and 3.1 import re sentences = """ You would stomp <mob> into …

Member Avatar for TrustyTony
0
110
Member Avatar for ktsangop

You should be able to use a dummy file by calling the linux command 'lockfile' from your programs (I never tried this, but it should work).

Member Avatar for ktsangop
0
378
Member Avatar for vsagarmb

An open file has a concept of 'position in the file'. After the first call to f.read(), the file position is at the end of the file. If you read again, you read an empty string. The solution is to go back to the beginning of the file [code=python] f.read() …

Member Avatar for vsagarmb
0
88
Member Avatar for valorien

The best way is to use the constructor 'int' with basis 16 to convert the hex values to integers, then use the bitwise operators &, |, ^ to perform the bitwise operations and use the 'hex' function to get the hexadecimal representation of the resulting integers. Here is an example …

Member Avatar for Gribouillis
0
14K
Member Avatar for pietromarchy

I know a method which uses the (great) [icode]lxml[/icode] module instead of ElementTree. The lxml.etree.tostring() method accepts a 'pretty_print' keyword argument. See the example here [url]http://codespeak.net/lxml/tutorial.html#serialisation[/url] . In your case [code=python] >>> from lxml import etree >>> root = etree.XML("<home><room>bedroom</room></home>") >>> print(etree.tostring(root, pretty_print=True)) <home> <room>bedroom</room> </home> [/code]

Member Avatar for pietromarchy
0
674
Member Avatar for bjoernh

Perhaps your file is using a BOM at the beginning. You could try open with mode 'utf-8-sig' instead of 'utf-8'.

Member Avatar for bjoernh
0
173
Member Avatar for oaktrees

You can use generators to iterate over your web page's lines [code=python] URL_TEMPLATE = ... def gen_lines(symbol, stat): url = URL_TEMPLATE % (symbol, stat) for line in urllib.urlopen(url): yield line.strip() def gen_rows(symbol, stat): for line in gen_lines(symbol, stat): row = line.split(",") row = [ x.strip('"') for x in row ] …

Member Avatar for oaktrees
0
86
Member Avatar for cableguy31

In linux, windows shares must be mounted. For example at home, I mount the (shared) C drive of another computer with IP address 192.168.2.4 like this [code=text] $ sudo mount -t cifs 192.168.2.4:C -o password="" /mnt/othercomp [/code] I can then access /mnt/othercomp like any other directory. I can also unmount …

Member Avatar for Gribouillis
0
188
Member Avatar for nramya82

You can use the string's 'startswith' method [code=python] cnt_char = 0 log_file = open("/tmp/new.txt") for lineno, line in enumerate(log_file): # lineno starts from 0 if line.startswith("#"): continue cnt_char += len(line) if cnt_char >= 1000: cnt_char -= len(line) break print("The first %d lines contain %d characters" % (lineno, cnt_char)) [/code] This …

Member Avatar for TrustyTony
0
113
Member Avatar for bharatvamsi

I suggest a subprocess, like this [code=python] from subprocess import Popen, PIPE tethereal = Popen('tethereal -i any "port 9060"', shell=True, stdout=PIPE) while True: data = tethereal.stdout.read(1024) if data == '': break print data [/code]

Member Avatar for Azeriah
0
296
Member Avatar for bjoernh

Try [icode]print repr(text)[/icode] to see what the string 'text' actually contains. Also if your file contains non ascii data, you should try the "rb" opening mode.

Member Avatar for griswolf
0
543
Member Avatar for linuxoidoz

You can use the [b]unidecode[/b] module available from here [url]http://pypi.python.org/pypi[/url] . For example [code=python] >>> str = unichr(int('00A9', 16)) >>> str u'\xa9' >>> from unidecode import unidecode >>> unidecode(str) '(c)' [/code] Also, you should not use 'str' as a variable name because it's the name of a builtin type.

Member Avatar for Gribouillis
0
202

The End.