Questions tagged [python]

530193 questions
4.9k

votes
30

answer
3.4m

Views

How do I check whether a file exists without exceptions?

How do I see if a file exists or not, without using the try statement?
spence91
2.3k

votes
11

answer
3.3m

Views

Iterating over dictionaries using 'for' loops

I am a bit puzzled by the following code: d = {'x': 1, 'y': 2, 'z': 3} for key in d: print key, 'corresponds to', d[key] What I don't understand is the key portion. How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a v...
TopChef
1.9k

votes
24

answer
3.2m

Views

How do I parse a string to a float or int in Python?

In Python, how can I parse a numeric string like '545.2222' to its corresponding float value, 542.2222? Or parse the string '31' to an integer, 31? I just want to know how to parse a float string to a float, and (separately) an int string to an int.
Tristan Havelick
3.2k

votes
15

answer
3.1m

Views

Does Python have a string 'contains' substring method?

I'm looking for a string.contains or string.indexof method in Python. I want to do: if not somestring.contains('blah'): continue
Blankman
4.2k

votes
30

answer
3m

Views

Calling an external command in Python

How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
freshWoWer
2.4k

votes
28

answer
2.9m

Views

Finding the index of an item given a list containing it in Python

For a list ['foo', 'bar', 'baz'] and an item in the list 'bar', how do I get its index (1) in Python?
Eugene M
1.9k

votes
30

answer
2.9m

Views

How to read a file line-by-line into a list?

How do I read every line of a file in Python and store each line as an element in a list? I want to read the file line by line and append each line to the end of the list.
Julie Raswick
2.6k

votes
18

answer
2.8m

Views

Using global variables in a function

How can I create or use a global variable in a function? If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
user46646
1.7k

votes
6

answer
2.8m

Views

How to get the number of elements in a list in Python?

items = [] items.append('apple') items.append('orange') items.append('banana') # FAKE METHOD:: items.amount() # Should return 3 How do I get the number of elements in the list?
y2k
3.1k

votes
22

answer
2.8m

Views

How do I list all files of a directory?

How can I list all files of a directory in Python and add them to a list?
duhhunjonn
1.1k

votes
9

answer
2.7m

Views

Converting integer to string in Python?

I want to convert an integer to a string in Python. I am typecasting it in vain: d = 15 d.str() When I try to convert it to string, it's showing an error like int doesn't have any attribute called str.
Hick
2.4k

votes
18

answer
2.6m

Views

How can I make a time delay in Python?

I would like to know how to put a time delay in a Python script.
user46646
2.1k

votes
13

answer
2.6m

Views

Add new keys to a dictionary?

Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method.
lfaraone
2.3k

votes
30

answer
2.6m

Views

How do I install pip on Windows?

pip is a replacement for easy_install. But should I install pip using easy_install on Windows? Is there a better way?
2.4k

votes
19

answer
2.5m

Views

Check if a given key already exists in a dictionary

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: if 'key1' in dict.keys(): print 'blah' else: print 'boo' I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
Mohan Gulati
2.1k

votes
30

answer
2.4m

Views

How to get the current time in Python

What is the module/method used to get the current time?
user46646
2.9k

votes
24

answer
2.4m

Views

Difference between append vs. extend list methods in Python

What's the difference between the list methods append() and extend()?
Claudiu
1.8k

votes
22

answer
2.4m

Views

Converting string into datetime

Short and simple. I've got a huge list of date-times like this as strings: Jun 1 2005 1:33PM Aug 28 1999 12:00AM I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects. Any help (even if it's just a kick in the right directio...
Oli
1.3k

votes
9

answer
2.3m

Views

Parsing values from a JSON file?

I have this JSON in a file: { 'maps': [ { 'id': 'blabla', 'iscategorical': '0' }, { 'id': 'blabla', 'iscategorical': '0' } ], 'masks': [ 'id': 'valore' ], 'om_points': 'value', 'parameters': [ 'id': 'valore' ] } I wrote this script which prints all of the json text: json_data=open(file_directory).re...
michele
1.7k

votes
11

answer
2.3m

Views

Is there a way to substring a string?

Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string? Maybe like myString[2:end]? If leaving the second part means 'till the end', if you leave the first part, does it start from the start?
Joan Venge
1.2k

votes
19

answer
2.2m

Views

Limiting floats to two decimal points

I want a to be rounded to 13.95. >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 The round function does not work the way I expected.
3.5k

votes
25

answer
2.2m

Views

How can I safely create a nested directory in Python?

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: import os file_path = '/my/directory/filename.txt' directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(dire...
Parand
1.2k

votes
19

answer
2.2m

Views

How do I remove an element from a list by index in Python?

How do I remove an element from a list by index in Python? I found the list.remove method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.
Joan Venge
1.6k

votes
15

answer
2m

Views

Find current directory and file's directory [duplicate]

This question already has an answer here: How to properly determine current script directory? 13 answers How to know/change current directory in Python shell? 6 answers In Python, what commands can I use to find: the current directory (where I was in the terminal when I ran the Python script), and...
John Howard
4.5k

votes
26

answer
2m

Views

What does if __name__ == “__main__”: do?

What does the if __name__ == '__main__': do? # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while True: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == '__main__': lock = thread.allocate_lock() thread.start_new_thread(...
Devoted
3.1k

votes
30

answer
2m

Views

How do I sort a dictionary by value?

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question How do I sort a list of di...
Gern Blanston
3k

votes
30

answer
1.9m

Views

How do I check if a list is empty?

For example, if passed the following: a = [] How do I check to see if a is empty?
Ray Vega
1.6k

votes
8

answer
1.9m

Views

How to lowercase a string in Python?

Is there a way to convert a string from uppercase, or even part uppercase to lowercase? E.g. Kilometers --> kilometers.
Benjamin Didur
8.7k

votes
30

answer
1.9m

Views

What does the “yield” keyword do?

What is the use of the yield keyword in Python? What does it do? For example, I'm trying to understand this code1: def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance + max_di...
Alex. S.
1.1k

votes
14

answer
1.7m

Views

How to determine a Python variable's type?

How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
user46646
564

votes
23

answer
1.7m

Views

How to define a two-dimensional array in Python

I want to define a two-dimensional array without an initialized length like this: Matrix = [][] but it does not work... I've tried the code below, but it is wrong too: Matrix = [5][5] Error: Traceback ... IndexError: list index out of range What is my mistake?
Masoud Abasian
1.3k

votes
14

answer
1.7m

Views

Select rows from a DataFrame based on values in a column in pandas

How to select rows from a DataFrame based on values in some column in pandas? In SQL I would use: select * from table where colume_name = some_value. I tried to look at pandas documentation but did not immediately find the answer.
szli
827

votes
10

answer
1.7m

Views

Correct way to write line to file?

I'm used to doing print >>f, 'hi there' However, it seems that print >> is getting deprecated. What is the recommended way to do the line above? Update: Regarding all those answers with '\n'...is this universal or Unix-specific? IE, should I be doing '\r\n' on Windows?
1.2k

votes
28

answer
1.7m

Views

Renaming columns in pandas

I have a DataFrame using pandas and column labels that I need to edit to replace the original column labels. I'd like to change the column names in a DataFrame A where the original column names are: ['$a', '$b', '$c', '$d', '$e'] to ['a', 'b', 'c', 'd', 'e']. I have the edited column names stored...
user1504276
1.7k

votes
21

answer
1.6m

Views

How do I install pip on macOS or OS X?

I spent most of the day yesterday searching for a clear answer for installing pip (package manager for Python). I can't find a good solution. How do I install it?
The System
524

votes
3

answer
1.6m

Views

How to convert list to string [duplicate]

Possible Duplicate: How to convert list into a string? How can I convert a list to a string using Python?
Nm3
1k

votes
1

answer
1.6m

Views

What IDE to use for Python? [closed]

What IDEs ('GUIs/editors') do others use for Python coding?
1.8k

votes
28

answer
1.6m

Views

How to concatenate two lists in Python?

How do I concatenate two lists in Python? Example: listone = [1, 2, 3] listtwo = [4, 5, 6] Expected outcome: >>> joinedlist [1, 2, 3, 4, 5, 6]
y2k
509

votes
9

answer
1.6m

Views

How to split a string into a list?

I want my Python function to split a sentence (input) and store each word in a list. My current code 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() # for each word in the line: for word in words: # print the...
Thanx
406

votes
14

answer
1.6m

Views

How to convert strings into integers in Python?

I have a tuple of tuples from a MySQL query like this: T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) I'd like to convert all the string elements into integers and put them back into a list of lists: T2 = [[13, 17, 18, 21, 32], [7, 11, 13,...
elfuego1