intent
stringlengths
4
183
snippet
stringlengths
2
1k
Python concat string with list
""" """.join(list)
Extending a list of lists in Python?
y = [[] for n in range(2)]
How do you read a file into a list in Python?
data = [line.strip() for line in open('C:/name/MyDocuments/numbers', 'r')]
How to delete all instances of a character in a string in python?
"""""".join([char for char in 'it is icy' if char != 'i'])
How to delete all instances of a character in a string in python?
re.sub('i', '', 'it is icy')
How to delete all instances of a character in a string in python?
"""it is icy""".replace('i', '')
How to delete all instances of a character in a string in python?
"""""".join([char for char in 'it is icy' if char != 'i'])
How to drop rows of Pandas DataFrame whose value in certain columns is NaN
df.dropna(subset=[1])
Searching a list of objects in Python
[x for x in myList if x.n == 30]
converting list of string to list of integer
nums = [int(x) for x in intstringlist]
converting list of string to list of integer
map(int, eval(input('Enter the unfriendly numbers: ')))
print in Python without newline or space
sys.stdout.write('.')
Python float to int conversion
int(round(2.51 * 100))
Find all files in directory with extension .txt
os.chdir('/mydir') for file in glob.glob('*.txt'): pass
Find all files in directory with extension .txt
for file in os.listdir('/mydir'): if file.endswith('.txt'): pass
Find all files in directory with extension .txt
for (root, dirs, files) in os.walk('/mydir'): for file in files: if file.endswith('.txt'): pass
Pandas (python) plot() without a legend
df.plot(legend=False)
loop through an IP address range
for i in range(256): for j in range(256): ip = ('192.168.%d.%d' % (i, j)) print(ip)
loop through an IP address range
for (i, j) in product(list(range(256)), list(range(256))): pass
loop through an IP address range
generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)
Python/Numpy: Convert list of bools to unsigned int
sum(1 << i for i, b in enumerate(x) if b)
Python: How to write multiple strings in one line?
target.write('%r\n%r\n%r\n' % (line1, line2, line3))
How to flatten a hetrogenous list of list into a single list in python?
[y for x in data for y in (x if isinstance(x, list) else [x])]
In Python, is it possible to escape newline characters when printing a string?
print('foo\nbar'.encode('string_escape'))
String Slicing Python
"""""".join(s.rsplit(',', 1))
Middle point of each pair of an numpy.array
(x[1:] + x[:-1]) / 2
Middle point of each pair of an numpy.array
x[:-1] + (x[1:] - x[:-1]) / 2
Reading unicode elements into numpy array
arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')
How to sort this list in Python?
l = sorted(l, key=itemgetter('time'), reverse=True)
How to sort this list in Python?
l = sorted(l, key=lambda a: a['time'], reverse=True)
pandas DataFrame filter regex
df.loc[df[0].str.contains('(Hel|Just)')]
How do I find the string between two special characters?
re.search('\\[(.*)\\]', your_string).group(1)
How to create a list of date string in 'yyyymmdd' format with Python Pandas?
[d.strftime('%Y%m%d') for d in pandas.date_range('20130226', '20130302')]
How to count the number of times something occurs inside a certain string?
"""The big brown fox is brown""".count('brown')
Sending post data from angularjs to django as JSON and not as raw content
json.loads(request.body)
Download file from web in Python 3
urllib.request.urlretrieve(url, file_name)
Split string into a list
text.split()
Split string into a list
text.split(',')
Split string into a list
line.split()
Replacing characters in a regex
[re.sub('(?<!\\d)\\.(?!\\d)', ' ', i) for i in s]
Sort A list of Strings Based on certain field
sorted(list_of_strings, key=lambda s: s.split(',')[1])
how to call multiple bash functions using | in python
subprocess.check_call('vasp | tee tee_output', shell=True)
How to eliminate all strings from a list
[element for element in lst if isinstance(element, int)]
How to eliminate all strings from a list
[element for element in lst if not isinstance(element, str)]
How do I sort a list of dictionaries by values of the dictionary in Python?
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
How do I sort a list of dictionaries by values of the dictionary in Python?
newlist = sorted(l, key=itemgetter('name'), reverse=True)
How do I sort a list of dictionaries by values of the dictionary in Python?
list_of_dicts.sort(key=operator.itemgetter('name'))
How do I sort a list of dictionaries by values of the dictionary in Python?
list_of_dicts.sort(key=operator.itemgetter('age'))
How to sort a Dataframe by the ocurrences in a column in Python (pandas)
df.groupby('prots').sum().sort('scores', ascending=False)
How can I access elements inside a list within a dictionary python?
""",""".join(trans['category'])
Variants of string concatenation?
"""""".join(['A', 'B', 'C', 'D'])
How do I get JSON data from RESTful service using Python?
json.load(urllib.request.urlopen('url'))
Removing an item from list matching a substring - Python
[x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]
Django filter by hour
Entry.objects.filter(pub_date__contains='08:00')
sort a list of dicts by x then by y
list.sort(key=lambda item: (item['points'], item['time']))
How to convert a Python datetime object to seconds
(t - datetime.datetime(1970, 1, 1)).total_seconds()
How to replace only part of the match with python re.sub
re.sub('(\\_a)?\\.([^\\.]*)$', '_suff.\\2', 'long.file.name.jpg')
How can I reload objects in my namespace in ipython
import imp imp.reload(module)
How to get a 16bit Unsigned integer in python
struct.unpack('H', struct.pack('h', number))
How can I use sum() function for a list in Python?
numlist = [float(x) for x in numlist]
Removing index column in pandas
df.to_csv(filename, index=False)
How to convert a string data to a JSON object in python?
json_data = json.loads(unescaped)
Is there a Python Library that contains a list of all the ascii characters?
[chr(i) for i in range(127)]
Python how to write to a binary file?
newFile.write(struct.pack('5B', *newFileBytes))
Python Regex - checking for a capital letter with a lowercase after
re.sub('^[A-Z0-9]*(?![a-z])', '', string)
Last Key in Python Dictionary
list(dict.keys())[-1]
write line to file
print('hi there', file=f)
write line to file
f = open('myfile', 'w') f.write('hi there\n')
write line to file
with open('somefile.txt', 'a') as the_file: the_file.write('Hello\n')
Python - Unicode to ASCII conversion
s.encode('iso-8859-15')
How to get max value in django ORM
AuthorizedEmail.objects.filter(group=group).order_by('-added')[0]
Python regex findall numbers and dots
re.findall('Test([0-9.]*[0-9]+)', text)
Python regex findall numbers and dots
re.findall('Test([\\d.]*\\d+)', text)
Is there a way to run powershell code in python
os.system('powershell.exe', 'script.ps1')
Sorting a dictionary of tuples in Python
b.sort(key=lambda x: x[1][2])
How do I get all the keys that are stored in the Cassandra column family with pycassa?
list(cf.get_range().get_keys())
how to create a file name with the current date & time in python?
datetime.datetime.now()
How to get the index of an integer from a list if the list contains a boolean?
next(i for i, x in enumerate(lst) if not isinstance(x, bool) and x == 1)
Subtract a value from every number in a list in Python?
a[:] = [(x - 13) for x in a]
Best way to choose a random file from a directory
random.choice(os.listdir('C:\\'))
How to get the highest element in absolute value in a numpy matrix?
max(x.min(), x.max(), key=abs)
Using Regular Expressions to extract specific urls in python
re.findall('"(http.*?)"', s, re.MULTILINE | re.DOTALL)
Using Regular Expressions to extract specific urls in python
re.findall('http://[^t][^s"]+\\.html', document)
Is there a function in Python to split a string without ignoring the spaces?
mystring.replace(' ', '! !').split('!')
Open file in Python
open(path, 'r')
Sum of multiple list of lists index wise
[[sum(item) for item in zip(*items)] for items in zip(*data)]
numpy: syntax/idiom to cast (n,) array to a (n, 1) array?
a[:, (np.newaxis)]