intent
stringlengths
4
183
snippet
stringlengths
2
1k
How do I split a multi-line string into multiple lines?
' a \n b \r\n c '.split('\n')
How to join mixed list (array) (with integers in it) in Python?
""":""".join(str(x) for x in b)
Fastest way to get the first object from a queryset in django?
Entry.objects.filter()[:1].get()
How to calculate the sum of all columns of a 2D numpy array (efficiently)
a.sum(axis=1)
Python, how to enable all warnings?
warnings.simplefilter('always')
Python printing without commas
print(' '.join(map(str, l)))
OSError: [WinError 193] %1 is not a valid Win32 application
subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])
How can I parse a time string containing milliseconds in it with python?
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
How can I convert a string with dot and comma into a float number in Python
my_float = float(my_string.replace(',', ''))
How can I convert a string with dot and comma into a float number in Python
float('123,456.908'.replace(',', ''))
In Python script, how do I set PYTHONPATH?
sys.path.append('/path/to/whatever')
Determining the unmatched portion of a string using a regex in Python
re.split('(\\W+)', 'Words, words, words.')
How to read data from Excel and write it to text file line by line?
file = open('Output.txt', 'a')
download a file over HTTP
urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
download a file over HTTP
u = urllib.request.urlopen(url)
download a file over HTTP
response = urllib.request.urlopen('http://www.example.com/') html = response.read()
download a file over HTTP
r = requests.get(url)
download a file over HTTP
response = requests.get(url, stream=True)
Python's argparse to show program's version with prog and version string formatting
parser.add_argument('--version', action='version', version='%(prog)s 2.0')
Remove key from dictionary in Python returning new dictionary
{i: d[i] for i in d if i != 'c'}
Merging two pandas dataframes
pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right'))
Python regular expression split() string
s.split(' ', 4)
How to read keyboard-input?
input('Enter your input:')
Auto reloading python Flask app upon code changes
app.run(debug=True)
Python save list and read data from file
pickle.dump(mylist, open('save.txt', 'wb'))
Numpy: Multiplying a matrix with a 3d tensor -- Suggestion
scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1)
How to create nested lists in python?
numpy.zeros((3, 3, 3))
Python: Cut off the last word of a sentence?
""" """.join(content.split(' ')[:-1])
Numpy convert scalars to arrays
x = np.asarray(x).reshape(1, -1)[(0), :]
Finding the sum of a nested list of ints
sum(sum(i) if isinstance(i, list) else i for i in L)
Convert hex to float
struct.unpack('!f', '470FC614'.decode('hex'))[0]
Python: Perform an operation on each dictionary value
my_dict.update((x, y * 2) for x, y in list(my_dict.items()))
Running bash script from within python
subprocess.call('sleep.sh', shell=True)
How would you make a comma-separated string from a list?
""",""".join(l)
How would you make a comma-separated string from a list?
myList = ','.join(map(str, myList))
Print a list in reverse order with range()?
list(reversed(list(range(10))))
How can i subtract two strings in python?
print('lamp, bag, mirror'.replace('bag,', ''))
python reverse tokens in a string
""".""".join(s.split('.')[::-1])
converting epoch time with milliseconds to datetime
datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
converting epoch time with milliseconds to datetime
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807 / 1000.0))
Getting the date of 7 days ago from current date in python
(datetime.datetime.now() - datetime.timedelta(days=7)).date()
How can I sum a column of a list?
print(sum(row[column] for row in data))
How can I sum a column of a list?
[sum(row[i] for row in array) for i in range(len(array[0]))]
How to encode text to base64 in python
base64.b64encode(bytes('your string', 'utf-8'))
How can I combine dictionaries with the same keys in python?
dict((k, [d[k] for d in dicts]) for k in dicts[0])
How can I combine dictionaries with the same keys in python?
{k: [d[k] for d in dicts] for k in dicts[0]}
How do I get the url parameter in a Flask view
request.args['myParam']
Identify duplicate values in a list in Python
[k for k, v in list(Counter(mylist).items()) if v > 1]
How do you modify sys.path in Google App Engine (Python)?
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'apps'))
How do you modify sys.path in Google App Engine (Python)?
sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))
Insert Null into SQLite3 in Python
db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,))
Flattening a shallow list in Python
[image for menuitem in list_of_menuitems for image in menuitem]
Append elements of a set to a list in Python
a.extend(b)
Append elements of a set to a list in Python
a.extend(list(b))
Python, Pandas : write content of DataFrame into text File
np.savetxt('c:\\data\\np.txt', df.values, fmt='%d')
Python, Pandas : write content of DataFrame into text File
df.to_csv('c:\\data\\pandas.txt', header=None, index=None, sep=' ', mode='a')
how to get the last part of a string before a certain character?
print(x.rpartition('-')[0])
how to get the last part of a string before a certain character?
print(x.rsplit('-', 1)[0])
FTP upload files Python
ftp.storlines('STOR ' + filename, open(filename, 'r'))
Write value to hidden element with selenium python script
browser.execute_script("document.getElementById('XYZ').value+='1'")
Combining two numpy arrays to form an array with the largest value from each array
np.maximum([2, 3, 4], [1, 5, 2])
How to print an entire list while not starting by the first item
print(l[3:] + l[:3])
loop over files
for fn in os.listdir('.'): if os.path.isfile(fn): pass
loop over files
for (root, dirs, filenames) in os.walk(source): for f in filenames: pass
Create random list of integers in Python
[int(1000 * random.random()) for i in range(10000)]
Using %f with strftime() in Python to get microseconds
datetime.datetime.now().strftime('%H:%M:%S.%f')
Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty
db.GqlQuery('SELECT * FROM Schedule WHERE station = $1', foo.key())
How to filter rows in pandas by regex
df.b.str.contains('^f')
What is the best way to print a table with delimiters in Python
print('\n'.join('\t'.join(str(col) for col in row) for row in tab))
Pandas: Delete rows based on multiple columns values
df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index()
String Formatting in Python 3
"""({:d} goals, ${:d})""".format(self.goals, self.penalties)
String Formatting in Python 3
"""({} goals, ${})""".format(self.goals, self.penalties)
String Formatting in Python 3
"""({0.goals} goals, ${0.penalties})""".format(self)
Convert list of lists to list of integers
[int(''.join(str(d) for d in x)) for x in L]
Convert list of lists to list of integers
[''.join(str(d) for d in x) for x in L]
Convert list of lists to list of integers
L = [int(''.join([str(y) for y in x])) for x in L]
How to write a list to a file with newlines in Python3
myfile.write('\n'.join(lines))
Removing an element from a list based on a predicate
[x for x in ['AAT', 'XAC', 'ANT', 'TTA'] if 'X' not in x and 'N' not in x]
python regular expression to remove repeated words
text = re.sub('\\b(\\w+)( \\1\\b)+', '\\1', text)
Counting non zero values in each column of a dataframe in python
df.astype(bool).sum(axis=1)
Python match string if it does not start with X
re.search('(?<!Distillr)\\\\AcroTray\\.exe', 'C:\\SomeDir\\AcroTray.exe')
String to list in Python
"""QH QD JC KD JS""".split()
Parsing XML in Python with regex
print(re.search('>.*<', line).group(0))
How to empty a file using Python
open(filename, 'w').close()
how to convert a string date into datetime format in python?
datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S.%f')
What's the fastest way to locate a list element within a list in python?
[index for index, item in enumerate(thelist) if item[0] == '332']
Python: trying to lower a string and remove non-alphanumeric characters aside from space
re.sub('[^\\sa-zA-Z0-9]', '', text).lower().strip()
Python: trying to lower a string and remove non-alphanumeric characters aside from space
re.sub('(?!\\s)[\\W_]', '', text).lower().strip()
Subscripting text in matplotlib labels
plt.plot(x, y, label='H\u2082O')
Subscripting text in matplotlib labels
plt.plot(x, y, label='$H_2O$')
Looping over a list in Python
[x for x in mylist if len(x) == 3]
Initialize a list of objects in Python
lst = [Object() for _ in range(100)]
Initialize a list of objects in Python
lst = [Object() for i in range(100)]
selenium how to get the content of href within some targeted class
self.driver.find_element_by_css_selector('.someclass a').get_attribute('href')
Joining Table/DataFrames with common Column in Python
df1.merge(df2, on='Date_Time')
insert variable values into a string in python
'first string is: %s, second one is: %s' % (str1, 'geo.tif')
Split a string by a delimiter in python
[x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')]
check if a directory exists and create it if necessary
if (not os.path.exists(directory)): os.makedirs(directory)
check if a directory exists and create it if necessary
os.makedirs(path)
check if a directory exists and create it if necessary
distutils.dir_util.mkpath(path)