text
stringlengths
185
26.5k
<s>[INST] Python reverse / invert a mapping Given a dictionary like so: my_map = { 'a': 1, 'b':2 } How can one invert this map to get: inv_map = { 1: 'a', 2: 'b' } EDITOR NOTE: map changed to my_map to avoid conflicts with the built-in function, map. Some comments may be affected below. [/INST] For Python 2.7.x inv_...
<s>[INST] Command Line Arguments In Python I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? Related What’s the best way to grab/parse command line arguments passed to a Python script? Implementing a â€...
<s>[INST] How to capitalize the first letter of each word in a string (Python)? s = 'the brown fox' ...do something here... s should be : 'The Brown Fox' What's the easiest way to do this? [/INST] The .title() method of a string (either ASCII or Unicode is fine) does this: >>> "hello world".title() 'Hello World' >>>...
<s>[INST] What is the quickest way to HTTP GET in Python? What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like: contents = url.get("http://example.com/foo/bar") But all I can find using Google are httplib and urllib - and I am unable ...
<s>[INST] How to check if type of a variable is string? Is there a way to check if the type of a variable in python is string.. like isinstance(x,int); for integer values? [/INST] In Python 2.x, you would do isinstance(s, basestring) basestring is the abstract superclass of str and unicode. It can be used to test wh...
<s>[INST] Why are there no ++ and --​ operators in Python? Why are there no ++ and -- operators in Python? [/INST] It's not because it doesn't make sense; it makes perfect sense to define "x++" as "x += 1, evaluating to the previous binding of x". If you want to know the original reason, you'll have to either wade t...
<s>[INST] What does functools.wraps do? In a comment on the answer to another question, someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly? [/INST] When you use a d...
<s>[INST] Should I put #! (shebang) in Python scripts, and what form should it take? Should I put the shebang in my Python scripts? In what form? #!/usr/bin/env python or #!/usr/local/bin/python Are these equally portable? Which form is used most? Note: the tornado project uses the shebang. On the other hand the Dja...
<s>[INST] Why are some float < integer comparisons four times slower than others? When comparing floats to integers, some pairs of values take much longer to be evaluated than other values of a similar magnitude. For example: >>> import timeit >>> timeit.timeit("562949953420000.7 < 562949953421000") # run 1 million tim...
<s>[INST] "is" operator behaves unexpectedly with integers Why does the following behave unexpectedly in Python? >>> a = 256 >>> b = 256 >>> a is b True # This is an expected result >>> a = 257 >>> b = 257 >>> a is b False # What happened here? Why is this False? >>> 257 is 257 True # Yet t...
<s>[INST] What does Ruby have that Python doesn't, and vice versa? There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefe...
<s>[INST] super() raises "TypeError: must be type, not classobj" for new-style class The following use of super() raises a TypeError: why? >>> from HTMLParser import HTMLParser >>> class TextParser(HTMLParser): ... def __init__(self): ... super(TextParser, self).__init__() ... self.all_data = [] .....
<s>[INST] Get difference between two lists I have two lists in Python, like these: temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get: temp3 = ['Three', 'Four'] Are there any...
<s>[INST] How do I get the path and name of the file that is currently executing? I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using execfile: script_1.py calls script_2.py. In turn, scrip...
<s>[INST] Pretty printing XML in Python What is the best way (or even the various ways) to pretty print xml in Python? [/INST] import xml.dom.minidom xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string) pretty_xml_as_string = xml.toprettyxml() </s>
<s>[INST] How to move a file in Python I looked into the Python os interface, but was unable to locate a method to move a file. How would I do the equivalent of $ mv ... in Python? >>> source_files = '/PATH/TO/FOLDER/*' >>> destination_folder = 'PATH/TO/FOLDER' >>> # equivalent of $ mv source_files destination_folder ...
<s>[INST] How do I find the location of Python module sources? How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the datetime module in particular, but I'm interested in a more general answer as well. [/IN...
<s>[INST] Measure time elapsed in Python? What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me. import timeit start = timeit.timeit() print "hello" ...
<s>[INST] clang error: unknown argument: '-mno-fused-madd' (python package installation failure) I get the following error when attempting to install psycopg2 via pip on Mavericks 10.9: clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] Not sure how to proceed and h...
<s>[INST] Dead simple argparse example wanted: 1 argument, 3 results The documentation for the argparse python module, while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. Likewise for many questions here on the stack. I don't need to do math on the command line or meddle with formatting...
<s>[INST] Python Image Library fails with message "decoder JPEG not available" - PIL PIL does support JPEG in my system. Whenever I do an upload, my code is failing with: File "PIL/Image.py", line 375, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder jpeg not available How c...
<s>[INST] Convert a Unicode string to a string in Python (containing extra symbols) How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string? [/INST] title = u"Klüft skräms inför på fédéral électoral große" import unicodedata unicodedata.normalize('NFKD', title).en...
<s>[INST] Converting from a string to boolean in Python? Does anyone know how to do convert from a string to a boolean in Python? I found this link. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc. EDIT: The reason I asked this is because I learned int("string"), from here. I t...
<s>[INST] Python: check if an object is a list or tuple (but not string) This is what I normally do in order to ascertain that the input is a list/tuple - but not a str. Because many times I stumbled upon bugs where a function passes a str object by mistake, and the target function does for x in lst assuming that lst i...
<s>[INST] How do I use Python's itertools.groupby()? I haven't been able to find an understandable explanation of how to actually use Python's itertools.groupby() function. What I'm trying to do is this: Take a list - in this case, the children of an objectified lxml element Divide it into groups based on some criter...
<s>[INST] Flatten (an irregular) list of lists in Python Yes, I know this subject has been covered before (here, here, here, here), but as far as I know, all solutions, except for one, fail on a list like this: L = [[[1, 2, 3], [4, 5]], 6] Where the desired output is [1, 2, 3, 4, 5, 6] Or perhaps even better, an iter...
<s>[INST] How to read large file, line by line in python I want to iterate over each line of an entire file. One way to do this is by reading the entire file, saving it to a list, then going over the line of interest. This method uses a lot of memory, so I am looking for an alternative. My code so far: for each_line in...
<s>[INST] How to sort (list/tuple) of lists/tuples? I have some data either in list contains lists, or list contains tuples. data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)] And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). W...
<s>[INST] How to re import an updated package while in Python Interpreter? I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file ...
<s>[INST] What is the purpose of the single underscore "_" variable in Python? What is the meaning of _ after for in this code? if tbh.bag: n = 0 for _ in tbh.bag.atom_set(): n += 1 [/INST] _ has 3 main conventional uses in Python: To hold the result of the last executed statement in an interactive inter...
<s>[INST] Fastest way to list all primes below N This is the best algorithm I could come up. def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timei...
<s>[INST] How do you express binary literals in Python? How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in P...
<s>[INST] Showing the stack trace from a running Python application I have this Python application that gets stuck from time to time and I can't find out where. Is there any way to signal Python interpreter to show you the exact code that's running? Some kind of on-the-fly stacktrace? Related questions: Print current...
<s>[INST] Creating a JSON response using Django and Python I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working. This is the server-side script: /* RECEIVE VALUE */ $validateValue=$_POST['validateValue']; $validateId=$_POST['validateId']; $validateError=$_...
<s>[INST] How do I correctly clean up a Python object? class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) __del__(self) above fails with an AttributeError exception. I understand Python doesn't guarantee the exi...
<s>[INST] Proper way to use **kwargs in Python What is the proper way to use **kwargs in Python when it comes to default values? kwargs returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? class ExampleClass: def __init...
<s>[INST] No module named pkg_resources I'm deploying a Django app to a dev server and am hitting this error when i run pip install requirements.txt: Traceback (most recent call last): File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module> from pkg_resources import load_entry_point ImportError: No mod...
<s>[INST] Rename Files in Python I'm trying to rename some files in a directory using Python. Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE I'm trying to use the os.path.split but it's not working properly. I have also considered using string ma...
<s>[INST] Find which version of package is installed with pip Using pip, is it possible to figure out which version of a package is currently installed? I know about pip install XYZ --upgrade but I am wondering if there is anything like pip info XYZ. If not what would be the best way to tell what version I am currentl...
<s>[INST] How to create a GUID/UUID in Python How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python? [/INST] If you're using Python 2.5 or later, the uuid module is already in...
<s>[INST] IndentationError: unindent does not match any outer indentation level When I compile the Python code below, I get IndentationError: unindent does not match any outer indentation level import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i ...
<s>[INST] A Transpose/Unzip Function in Python (inverse of zip) I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become....
<s>[INST] What is the most "pythonic" way to iterate over a list in chunks? I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm ite...
<s>[INST] What exactly do "u" and "r" string flags do in Python, and what are raw string literals? While asking this question, I realized I didn't know much about raw strings. For somebody claiming to be a Django trainer, this sucks. I know what an encoding is, and I know what u alone does since I get what is Unicode. ...
<s>[INST] How to save a Python interactive session? I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into ...
<s>[INST] Python: about catching ANY exception How can I write a try/except block that catches all exceptions? [/INST] Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception: import traceback import logging try: whatever() except Exception as e: logging....
<s>[INST] Check if a Python list item contains a string inside another string I have a list: my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456'] and want to search for items that contain the string 'abc'. How can I do that? if 'abc' in my_list: would check if 'abc' exists in the list but it is a part of 'abc-123' ...
<s>[INST] Elegant Python function to convert CamelCase to snake_case? Example: >>> convert('CamelCase') 'camel_case' [/INST] This is pretty thorough: def convert(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() Works with all these (and doesn't h...
<s>[INST] Maximum and Minimum values for ints I am looking for minimum and maximum values for integers in python. For eg., in Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE. Is there something like this in python? [/INST] In Python 2, there's sys.maxint: >>> sys.maxint 9223372036854775807 And you can calculate...
<s>[INST] Is it worth using Python's re.compile? Is there any benefit in using compile for regular expressions in Python? h = re.compile('hello') h.match('hello world') vs re.match('hello', 'hello world') [/INST] I've had a lot of experience running a compiled regex 1000s of times versus compiling on-the-fly, and ha...
<s>[INST] Why is 'x' in ('x',) faster than 'x' == 'x'? >>> timeit.timeit("'x' in ('x',)") 0.04869917374131205 >>> timeit.timeit("'x' == 'x'") 0.06144205736110564 Also works for tuples with multiple elements, both versions seem to grow linearly: >>> timeit.timeit("'x' in ('x', 'y')") 0.04866674801541748 >>> timeit.time...
<s>[INST] How do I run Python code from Sublime Text 2? I want to set up a complete Python IDE in Sublime Text 2. I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ? [/INST] Tools -> Build System -> (choose) Python then: To Run: Tools -> Build ...
<s>[INST] How to print a class or objects of class using print()? I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I get an output like this: <__main__.Foobar instance at 0x7ff2a18c> Is there a way I can set the printing behaviour (or the string representatio...
<s>[INST] Convert a list of characters into a string If I have a list of chars: a = ['a','b','c','d'] How do I convert it into a single string? a = 'abcd' [/INST] Use the join method of the empty string to join all of the strings together with the empty string in between, like so: >>> a = ['a', 'b', 'c', 'd'] >>> ''...
<s>[INST] What's the idiomatic syntax for prepending to a short python list? list.append() is the obvious choice for adding to the end of a list. Here's a reasonable explanation for the missing list.prepend(). Assuming my list is short and performance concerns are negligible, is list.insert(0, x) or list[0:0] = [x...
<s>[INST] Which exception should I raise on bad/illegal argument combinations in Python? I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: def import_to_orm(name, save=False, recurse=False): """ :...
<s>[INST] Python urlencode querystring I am trying to urlencode this string before I submit. queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"]; [/INST] Python 2 What you're looking for is urllib.quote_plus: >>> urllib.quote_plus('string_of_characters_l...
<s>[INST] How to check Django version I have to use Python and Django for our application. So I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django succesfuly. But how do I make sure whether Django uses the 2.6 or 2.7 version and what version of m...
<s>[INST] Fastest way to check if a value exist in a list I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know all values in the list are unique like my example. My first methods I try is(3.8sec in my real code): a = [4,2,3,1,5,6] if...
<s>[INST] How do I get my python program to sleep for 50 milliseconds? How do I get my python program to sleep for 50 milliseconds? [/INST] Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from time...
<s>[INST] What's the difference between eval, exec, and compile in Python? I've been looking at dynamic evaluation of Python code, and come across the eval() and compile() functions, and the exec statement. Can someone please explain the difference between eval and exec, and how the different modes of compile() fit in?...
<s>[INST] How to find out the number of CPUs using python I want to know the number of CPUs on the local machine using Python. The result should be user/real as output by time(1) when called with an optimally scaling userspace-only program. [/INST] If you have python with a version >= 2.6 you can simply use import mul...
<s>[INST] What is the best way to remove accents in a Python unicode string? I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the Web an elegant way to do this in Java: convert the Unicode string to its long normalized form (with a separate character for letters an...
<s>[INST] Simple Digit Recognition OCR in OpenCV-Python I am trying to implement a "Digit Recognition OCR" in OpenCV-Python (cv2). It is just for learning purposes. I would like to learn both KNearest and SVM features in OpenCV. I have 100 samples (i.e. images) of each digit. I would like to train with them. There is ...
<s>[INST] How do I make python to wait for a pressed key I want my script to wait until the user presses any key. How do I do that? [/INST] One way to do this in Python 2, is to use raw_input(): raw_input("Press Enter to continue...") In python3 it's just input() </s>
<s>[INST] Find all packages installed with easy_install/pip? Is there a way to find all Python PyPI packages that were installed with easy_install or pip? I mean, excluding everything that was/is installed with the distributions tools (in this case apt-get on Debian). [/INST] pip freeze will output a list of installe...
<s>[INST] Short Description of Scoping Rules What exactly are the Python scoping rules? If I have some code: code1 class Foo: code2 def spam..... code3 for code4..: code5 x() Where is x found? Some possible choices include the list above: In the enclosing source file In the class name...
<s>[INST] Does Python have an ordered set? Python has an ordered dictionary, what about an ordered set? [/INST] There is an ordered set recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same ...
<s>[INST] time.sleep -- sleeps thread or process? In Python for the *nix, does time.sleep() block the thread or the process? [/INST] It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep(), the substantive part of the sleep operation is wrapped in a ...
<s>[INST] Python list of lists, changes reflected across sublists unexpectedly I needed to create a list of lists in Python, so I typed the following: myList = [[1] * 4] * 3 The list looked like this: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] Then I changed one of the innermost values: myList[0][0] = 5 Now ...
<s>[INST] How to break out of multiple loops in Python? Given the following code (that doesn't work): while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #...
<s>[INST] How to install python3 version of package via pip on Ubuntu? I have both python2.7 and python3.2 installed in Ubuntu 12.04. The symbolic link python links to python2.7. When I type: sudo pip install package-name It will default install python2 version of package-name. Some package supports both python2 and p...
<s>[INST] In Matplotlib, what does the argument mean in fig.add_subplot(111)? Sometimes I come across code such as this: import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] fig = plt.figure() fig.add_subplot(111) plt.scatter(x, y) plt.show() Which produces: I've been reading the documentation li...
<s>[INST] python open built-in function: difference between modes a, a+, w, w+, and r+? In the python built-in open function, what is the exact difference between the modes w, a, w+, a+, and r+? In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files f...
<s>[INST] How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? I need a way to tell what mode the shell is in from within the shell. I've tried looking at the platform module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": ...
<s>[INST] Setting the correct encoding when piping stdout in Python When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: # -*- coding: utf-8 -*- print u"åäö" will work fine when run normally, but fail with: UnicodeEncod...
<s>[INST] Difference between Python's Generators and Iterators What is the difference between iterators and generators? Some examples for when you would use each case would be helpful. [/INST] iterator is a more general concept: any object whose class has a next method (__next__ in Python 3) and an __iter__ method tha...
<s>[INST] Python: user input and commandline arguments How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line? [/INST] var = raw_input("Please enter something: ") print "you entered", var </s>
<s>[INST] Elegant ways to support equivalence ("equality") in Python classes When writing custom classes it is often important to allow equivalence by means of the == and != operators. In Python, this is made possible by implementing the __eq__ and __ne__ special methods, respectively. The easiest way I've found to do ...
<s>[INST] How to use 'super' in Python? Can someone explain to me the difference between doing: class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() and this: class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) I've seen super being used quite ...
<s>[INST] How do I use raw_input in Python 3 import sys print (sys.platform) print (2 ** 100) raw_input( ) I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1 What should I do to fix this? [/INST] raw_input() was renamed to input() From http:...
<s>[INST] How do you convert a Python time.struct_time object into a datetime object? How do you convert a Python time.struct_time object into a datetime.datetime object? I have a library that provides the first one and a second library that wants the second one... [/INST] Use time.mktime() to convert the time tuple (...
<s>[INST] Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup: Python 2.6.1 64bit Django 1.2.1 MySQL 5.1.47 osx10.6 64bit I create a virtualenvwr...
<s>[INST] What is the python "with" statement designed for? I came across the Python with statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking: What is the Python with stateme...
<s>[INST] Python: How to import other Python files How do I import other files in Python? How exactly can I import a specific python file like import file.py? How to import a folder instead of a specific file? I want to load a Python file dynamically in runtime, based on user input. I want to know how to take from the...
<s>[INST] Does Python's time.time() return the local or UTC timestamp? Does time.time() in the Python time module return the system's time or the time in UTC? [/INST] The time.time() function returns the number of seconds since the epoch as seconds in UTC. Here is some sample output I ran on my computer, converting it...
<s>[INST] Split string into a list in Python I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that? def split_line(text): # split the text words = text.split() # f...
<s>[INST] What's the proper way to install pip, virtualenv, and distribute for Python? Short Question What is the proper way to install pip, virtualenv, and distribute? Background In my answer to SO question 4314376, I recommended using ez_setup so that you could then install pip and virtualenv as follows: curl -O ht...
<s>[INST] How to make a Python script standalone executable to run without ANY dependency? I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source. So, is there a way to compile Python scripts to standalone executables? [/INST...
<s>[INST] Why isn't Python very good for functional programming? I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in this question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for...
<s>[INST] How to empty a list in Python? It seems so "dirty" emptying a list in this way: while len(alist) > 0 : alist.pop() Does a clear way exist to do that? [/INST] This actually removes the contents from the list, not replaces the old label with a new empty list del lst[:] example: lst1 = [1, 2, 3] lst2 = lst1 d...
<s>[INST] Remove specific characters from a string in python I'm trying to remove specific characters from a string using python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string. for char in line: if char in " ?.!/;:": line.replace(char,'') How do I do this proper...
<s>[INST] What is memoization and how can I use it in Python? I just started Python and I've got no idea what memoization is and how to use it. Also, may I have a simplified example? [/INST] Memoization effectively refers to remembering ("memoization" -> "memorandum" -> to be remembered) results of method calls based ...
<s>[INST] How to overcome "datetime.datetime not JSON serializable" in python? I have a basic dict as follows: sample = {} sample['title'] = "String" sample['somedate'] = somedatetimehere When I try to do jsonify(sample) I get: TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable Wha...
<s>[INST] Python Print String To Text File I'm using Python to open a text document: text_file = open("Output.txt", "w") text_file.write("Purchase Amount: " 'TotalAmount') text_file.close() I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this? [/INST]...
<s>[INST] Writing a list to a file with Python Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters? file.writelines(["%s\n" % item for item in list]) It seems like there would be a standard way... [/INST] EDIT Adding info from Thomas' comment Don't forget to open...
<s>[INST] Python, extract file name from path, no matter what the os/path format Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be? For example, I'd like all of these paths to return me c: a/b/c/ a/b/c \a\b\c \a\b\c\ a\b\c a/b/../../a/b/c/ a/b/.....
<s>[INST] What's the difference between a Python module and a Python package? What's the difference between a Python module and a Python package? See also: What's the difference between "package" and "module" (for other languages) [/INST] Any Python file is a module, its name being the file's base name without the .py...
<s>[INST] Cannot install Lxml on Mac os x 10.9 I want to install Lxml so I can then install Scrapy. When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error: In file included from src/lxml/lxml.etree.c:314: /private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error...
<s>[INST] Generator Expressions vs. List Comprehension When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] [/INST] John's answer is good (that list comprehensions are better wh...