2,646 Posted Topics
Re: I ran [url=http://www.logilab.org/project/pylint]pylint[/url] on this code. Here is the result (note that this depends on my personal configuration of pylint, it may give a different result on your system) [code] $ pylint --disable-msg W0311 bad.py ************* Module bad C: 6: Line too long (93/80) C: 8: Line too long (132/80) … | |
Re: You can also use format [code=python] message = "z's value is {z:0{digits}n}".format(z=2, digits=3) print(message) [/code] | |
Re: You can get the path to the site-packages directory like this [code=python] >>> import os >>> os.path.join(os.path.split(os.__file__)[0], "site-packages") '/usr/lib64/python2.6/site-packages' [/code] With python 3: [code=python] >>> import os >>> os.path.join(os.path.split(os.__file__)[0], "site-packages") '/usr/local/lib/python3.1/site-packages' [/code] (on the same machine). However, you shouldn't normally need to put the site-packages in sys.path yourself. I'd like … | |
Re: You probably need at least libtk-devel and libtcl-devel to build with tkinter. | |
Re: Did you try [code=python] print(charp_getitem(d, 20)) [/code] ? | |
Re: I don't know OS X, but couldn't you run idle with the -s option and write a startup file, say startup.py containing os.chdir(os.path.expanduser('~/Documents/Python/')), and then set the [url=http://docs.python.org/library/idle.html?highlight=idlestartup#startup]IDLESTARTUP[/url] environment variable to startup.py ? | |
Re: I think you could try something like this [code=python] def key(line): return tuple(line.strip().split()[2:6]) def make_key_set(file_path): return set(key(line) for line in open(file_path)) def filtered_lines(file_path1, file_path2): key_set = make_key_set(file_path2) return (line for line in open(file_path1) if key(line) in key_set) if __name__ == "__main__": file3 = open("file3", "w") for line in filtered_lines("file1", "file2"): … | |
Re: You MUST NOT install packages using source code and "./configure, make, make install". It's the last resort for programs for which no mandriva package exist. The correct way to do it is to install packages with the mandriva software manager. You won't be able to manage the packages yourself. It's … | |
Re: A simple thing to do is to put the file "graphics.py" in a folder named "site-packages" which is a subfolder of your python Lib folder. You should locate it easily on your computer. Another solution is to create another folder where you want to put importable modules, for example "C:/pymods" … | |
Re: You can also do this without a loop [code=python] #!/usr/bin/env python import re nonletters = re.compile("[^a-zA-Z]+") def letters_only(mystring): return nonletters.sub(lambda m: '', mystring) print(letters_only("Madam, in Eden I'm Adam!")) """ my output ---> MadaminEdenImAdam """ [/code] | |
Re: When you open a file, the cursor is at the beginning of the file. However [code=python] myfile.seek(0) [/code] goes to the beginning of the file. [url=http://docs.python.org/library/stdtypes.html?highlight=seek#file.seek]Finally, read this.[/url] | |
Re: You can use regular expressions and the re.sub function, like this [code=python] import re special = re.compile(r"[etn]") def escape(match): return "\\" + match.group(0) if __name__ == "__main__": text = "This is a test sentence." print text print special.sub(escape, text) r""" my output ---> This is a test sentence. This is … | |
Re: Yes I think that you must always incref the results. Also consider using Py_XINCREF and Py_XDECREF which handle the case where you pass a null pointer. A good idea is to test your code with the help of the [icode]sys.getrefcount()[/icode] function. For example [code=python] >>> class A: ... pass ... … | |
Re: A possible implementation of remove_all [code=python] import re def remove_all(sub, s): """ >>> remove_all('an', 'banana') 'ba' >>> remove_all('cyc', 'bicycle') 'bile' >>> remove_all('iss', 'Mississippi') 'Mippi' """ return re.sub(re.escape(sub), '', s) if __name__ == '__main__': import doctest doctest.testmod() [/code] Note that a regex is compiled on each call. | |
Re: [QUOTE=PixelHead777;1023043]At the easy risk of asking something already asked a hundred times... Curses doesn't work for me. I use 2.6 on a Vista It gives an error saying it can't call up a part of the module that came with the program. ... Uhm... help.. T_T ~Pixel[/QUOTE] You had 2 … | |
Re: Did you read this in your assingment ? [b] Although it can be helpful to you to discuss your program with other people, and that is a reasonable thing to do and a good way to learn, the work you hand in must ultimately be your own work. This is … | |
Re: There are many examples of extensions written in C or C++. For example the numpy package implements classes written in C. One of the main reasons to do this is that C or C++ run much faster than python, especially in numerical analysis applications. | |
Re: A nice tool is [url=http://sphinx.pocoo.org/]sphinx[/url] which converts text written in rich text format to html. | |
Re: It already exists (py >= 2.6) [code=python] from itertools import product myproduct = set(product(myset1, myset2)) [/code] | |
Re: In the "if choice" sequence, you should replace [b]raw_input[/b] by [b]input[/b] because you want the user input to be interpreted as a number and not as a string. Also [url=http://www.daniweb.com/forums/announcement114-3.html]read this[/url] about how to post python code in this forum. | |
Suppose that I have a program named myprog, and I type this in a shell [code] $ myprog -z hello -m "this is a message" [/code] The function main in myprog will receive a char** argv containing the following strings [code] "-z", "hello", "-m", "this is a message" [/code] So … | |
Re: try [code=python] string2 = "Random Number is\n{value:^16}".format(value = string1) [/code] Also, you can read [url=http://www.daniweb.com/code/snippet232375.html]this[/url] :) | |
Re: You can enter a python list and then convert it using eval [code=python] userInput = input("Enter a python list: ") mylist = eval(userInput.strip()) # check that it's a list assert(isinstance(mylist, list)) print(mylist) """ running the program in a shell: $ python3 myinput.py Enter a python list: [3, 4, 5] [3, … | |
Re: I discovered a new python book today [url=http://www.linuxtopia.org/online_books/programming_books/python_programming/index.html]http://www.linuxtopia.org/online_books/programming_books/python_programming/index.html[/url]. | |
Re: In python 3 you can do [code=python] from collections import OrderedDict [/code] which gives you a class which remembers insertion order. For older pythons, you can try to use a class found on the web like [url=http://code.activestate.com/recipes/107747/]http://code.activestate.com/recipes/107747/[/url]. | |
Printing a convenient [url=http://en.wikipedia.org/wiki/ANSI_escape_sequence]ansi escape sequence[/url] clears the terminal (if you're running python from a terminal). Similar techniques could be used to print in colors. | |
Re: You could use [code=python] reply = raw_input("Enter your choice: ") reply = reply.strip() if reply not in ("1", "2"): print("Not a valid choice") else: reply = int(reply) [/code] | |
Re: [QUOTE=pyprog;1026865]Hey, everyone. I know how to strip certain characters from a string using for loop. Can you give an example of how that can be done with the use of while loop?[/QUOTE] Please post your code with the for loop and we'll rewrite it with a while loop :) | |
Re: It's probably a question of setting the process' priority. On linux, you would use the [b]renice[/b] command. | |
Re: [QUOTE=vegaseat;1026365](removed first line since I am using Python25).[/QUOTE] Why don't you install 2.6 ? It's even better. | |
Re: You should write algorithms describing what you want to do [code] # first algorithm sum starts from 0 i starts from lo while i <= hi: add i to sum increase i # second algorithm create a new empty list i starts from m while i <= n: append i … | |
Re: I think you should learn python now and later go into C++. Python will teach you programming and give you an object oriented way of thinking. This will be very useful for the C++ class. Later, you'll discover that it takes hundreds of lines to do in C++ what you … | |
Re: This should work [code=python] value = min(x for x in temperature_sequence if x > 0) [/code] Note: this raises ValueError if all temperatures are below 0. | |
Re: The Pmw megawidgets toolkit for tkinter implements a mechanism for data validation. For example the background color of an entry field turns pink if you enter bad input. Although this module is old, it could be a good starting point for experimenting with data validation. You can create your own … | |
![]() | Re: It's not a very good function interface. You should not need to pass the names of variables local to the function. The question is rather when and why you want to return either x and y or y and z. |
Re: Also note that the line looks like an xml tag. If your file is an xml file, you could parse it with lxml for example. | |
Re: Indeed [code=python] Python 3.1.1 (r311:74480, Sep 8 2009, 15:48:28) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print(repr(input("enter your input: "))) enter your input: 4, 5 '4, 5' [/code] So the input returned a single string. | |
Re: Can't you spawn 4 python processes, each of them sending 1000 mails ? | |
Re: Did you try [icode]python -v[/icode] ? Please post the traceback between code tags [url=http://www.daniweb.com/forums/announcement114-3.html]http://www.daniweb.com/forums/announcement114-3.html[/url]. | |
Re: Python is fundamentaly object oriented, so yes, I think we should write as much OO code as possible in this forum. It's also the good way for students to learn python. | |
Does anyone know how I can test if an object's type is a builtin type or a user defined type ? | |
Re: [code=python] s='1234444432187667890000568984' print("\n".join(("I found %d: %d" % (s.count(str(i)), i)) for i in range(10))) [/code] | |
Re: You can try this [code=python] def dos2unix(my_string): return my_string.replace("\r\n", "\n") # is it \n\r instead ? if __name__ == "__main__": dos_content = "line1\r\nline2\r\nline3\r\n" unix_content = dos2unix(dos_content) print repr(unix_content) """my output ---> 'line1\nline2\nline3\n' """ [/code] Note that there are numerous other potential issues: if your cgi scripts use the win32 api, … | |
Re: A possible use of static methods is to add [b]constructors[/b] to a class, like in this example [code=python] class Person(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return "Person({name}, {age})".format(name=self.name, age=self.age) @staticmethod def from_sequence(seq): name, age = list(seq) return Person(name, age) @staticmethod def from_dict(dic): return … | |
Re: [QUOTE=gmilby;1021702]Any ideas when python 3 will be the norm? it doesn't appear ANYONE is racing forward... have to wonder how extensive the bugs are in the new version...[/QUOTE] On the contrary, everybody is racing forward. The problem is that we all use third party python modules which are not yet … | |
Re: Why don't you just use shuffle ? [code=python] from random import shuffle def random_unique(sequence): L = list(sequence) shuffle(L) return iter(L) for x in random_unique(range(10)): print(x) [/code] | |
Re: I suggest [code=python] >>> print("\n" * 40) [/code] Or even better [code=python] >>> def clear(): ... print("\n"*40) >>> clear() [/code] Last one: [code=python] >>> def clear(): ... import sys ... for i in range(40): ... print(sys.ps1) [/code] | |
This snippet shows a fast and efficient way to cut strings in substrings with a fixed length (note that the last substring may be smaller). | |
Re: I wrote a [url=http://www.daniweb.com/code/snippet217111.html]code snippet[/url] for this last year :) |
The End.