I am looking for a way to easily split a python array in half.
So that if I have an array:
A = [0,1,2,3,4,5]
I would be able to get:
B = [0,1,2]
C = [3,4,5]
In Python, I want to make selected instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)
From Building Skills in Python:
"A file name like exercise_1.py is better than the name execise-1.py. We can run both programs equally well from the command line, but the name with the hyphen limits our ability to write larger and more sophisticated programs."
Why?
Hello,
I tried to fetch source of 4chan site, and get links to threads.
I have problem with regexp (isn't working). Source:
import urllib2, re
req = urllib2.Request('http://boards.4chan.org/wg/')
resp = urllib2.urlopen(req)
html = resp.read()
print re.findall("res/[0-9]+", html)
#print re.findall("^res/[0-9]+$", html)
The problem is that:
print re.findall("res/[0-9]+", html)
is giving duplicates.
I can't use:
print re.findall("^res/[0-9]+$", html)
I have read python docs but they didn't help.
It seems pretty common to me to have an argument, in a dynamically typed language that is either an Object or a key to lookup that object. For instance when I'm working with a database I might have a method getMyRelatedStuff(person)
All I really need to lookup the related stuff is the id of the person so my method could look like this in python:
def getMyRelatedStuff(person_or_id):
id = person_or_id.id if isinstance(person,User) else person_or_id
#do some lookup
Or going the other direction:
def someFileStuff(file_or_name):
file = file_or_name if hasattr(file,'write') else open(file_or_name)
I'm working with python and mysql and I want to verify that a certain entry is compressed in the db. Ie:
cur = db.getCursor()
cur.execute('''select compressed_column from table where id=12345''')
res = cur.fetchall()
at this point I would like to verify that the entry is compressed (ie in order to work with the data you would have to use select uncompress(compressed_column)..). Ideas?
Hi all,
How do I convert a string to a date object in python?
The string would be: "24052010" (corresponding to the format: "%d%m%Y")
I DON'T want a datetime object.
I suspect that I'm asking a trivial question but I searched and couldn't find it neither on stackoverflow nor on google.
Thank you,
Elif
I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match:
if paid[j].find(d)>=0:
#BLAH BLAH
If 'd' were an array, what is the most efficient way to see if the string contained in paid[j] has a match to any value in 'd'?
Given the following function:
def foo(a, b, c):
pass
How would one obtain a list/tuple/dict/etc of the arguments passed in?
Specifically, I'm looking for Python's version of JavaScript's arguments keyword or PHP's func_get_args() method.
What I'm not looking for is a solution using *args or **kwargs; I need to specify the argument names in the function definition (to ensure they're being passed in) but within the function I want to work with them in a list- or dict-style structure.
Is there any reason behind using date(January 1st, 1970) as standard for time manipulation? I have seen this standard in Java as well as in Python. These two languages I am aware of. Is other popular languages also follows the same standard?
Please describe.
Hi everyone. I'd ideally like a vim answer to this:
I want to change
[*, 1, *, *] to [*, 2, *, *]
Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example
[0, 1, 0, 1] to [0, 2, 0, 1]
[1, 1, 1, 1] to [1, 2, 1, 1]
If people know how to do this in perl or python or whatever, that would be equally good.
Cheers
I want to make my Python Class behave in such a way that when any Class method is called a default method is executed first without explicitly specifying this in the called Class. An example may help :)
Class animals:
def _internalMethod():
self.respires = True
def cat():
self._internalMethod()
self.name = 'cat'
def dog():
self._internalMethod()
self.name = 'dog'
I want _internalMethod() to be called automatically when any method is called from an instance of animals, rather than stating it explicitly in the def of each method. Is there an elegant way to do this?
Cheers,
We are in web era standalone applications are almost gone everyone wants their internet application to run inside browser, programming languages like Ruby, Python and scala are becoming more and more mainstream.
Sometimes I wonder what these programming language offer which make them top choice of IT companies, if I plan to become a freelance web developer is it worth learning C# or Java. I read beginner's book for both of them, but to master any of them require some time investment.
Hi folks,
I'm currently using os.popen() but have been recommended to use subprocess.popen() instead.
Any ideas on how I can integrate this?
It would be cool and fun to have a Python shell accessible on a Django app. But I reckon that it might be a bit complex to implement.
I guess I would have to retrieve the subprocess, as a new request comes in.
Any ideas?
I'm looking for a regex to search my python program to find all lines where foo, but not bar, is passed into a method as a keyword argument. I'm playing around with lookahead and lookbehind assertions, but not having much luck.
Any help?
Thanks
I have a list which contains a number of things:
lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2. Is there a neater way to do it than itertools' dropwhile and next?
first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista))
I did use [item for item in lista if len(item)>2][0] at first, but that requires python to generate the entire list first.
Consider I have an array of elements out of which I want to create a new 'iterable' which on every next applies a custom 'transformation'. What's the proper way of doing it under python 2.x?
For people familiar with Java, the equivalent is Iterables#transform from google's collections framework.
Does anyone know of a simple open source proxy capable of running on google app engine or where to start in making one? (preferably in python, I'm trying to bypass a site blocking system)
I'm wondering how to implement prototypal inheritance in Python. It seems like the way to do this would be to either
use a metaclass to cause instantiations to actually be classes, rather than objects, or
use some magical powers to transform an existing object into a class.
The second method would seem to be more flexible, in that it could be applied to existing objects of varied types, while the first would likely be more convenient for typical use cases.
Insights on the practicality of these two approaches, as well as alternative suggestions, are hereby requested.
Hi,
Is there any reason behind using this date as standard for time manipulation? I have seen this standard in Java as well as in Python. These two languages I am aware of. Is other popular languages also follows the same standard?
Please describe.
I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties).
Example code:
class my_class(object):
@register(prop1,prop2)
def my_method( arg1,arg2 ):
# method code here...
@register(prop3,prop4)
def my_other_method( arg1,arg2 ):
# method code here...
I want that when loading is done, somewhere there will be a dict containing:
{ "my_class.my_method" : ( prop1, prop2 )
"my_class.my_other_method" : ( prop3, prop4 ) }
Is this possible?
Hi,
i have a large dictionary I'd like to save. I have pickled it using cPickle.dumps and saved the result into a TextField. When trying to retrieve it (cPicle.loads) i get the following error:
loads() argument 1 must be string, not unicode
Does anybody have any experience in serializing python objects and storing them in a DB using Django? Thanks in advance.
I have searched all over and can't figure out how to get a list of all the design documents for a specific database in CouchDB using couchdbkit for python?
i try to write this code to process Arabic language by python
import codecs
file = codecs.open("C:\Python27\CCA_raw_utf8.txt","r","utf-8")
text= file.read()
####################################
print "\n "," --------------------------------------------"
text=text[1:]
words=text.split()
for w in words:
if w == unicode ("?????","utf-8"):
print w
but it doesn't and take error " if w == unicode ("?????","utf-8"):
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 0: invalid continuation byte "
why program gives this result and how we can correct that??