Create list `instancelist` containing 29 objects of type MyClass

instancelist = [MyClass() for i in range(29)]

VAR_STR = [MyClass() for i in range(29)]


Taking the results of a bash command "awk '{print $10, $11}' test.txt > test2.txt"

os.system("awk '{print $10, $11}' test.txt > test2.txt")


selenium wait for driver `driver` 60 seconds before throwing a NoSuchElementExceptions exception


selenium webdriver switch to frame 'frameName'


Save plot `plt` as png file 'filename.png'


Save matplotlib graph to image file `filename.png` at a resolution of `300 dpi`


search for regex pattern 'Test(.*)print' in string `testStr` including new line character '\n'


Enclose numbers in quotes in a string `This is number 1 and this is number 22`

re.sub('(\\d+)', '"\\1"', 'This is number 1 and this is number 22')


Importing file `file` from folder '/path/to/application/app/folder'

sys.path.insert(0, '/path/to/application/app/folder')
import file

sys.path.insert(0, 'VAR_STR')
import VAR_STR


append the sum of each tuple pair in the grouped list `list1` and list `list2` elements to list `list3`

list3 = [(a + b) for a, b in zip(list1, list2)]

VAR_STR = [(a + b) for a, b in zip(VAR_STR, VAR_STR)]


remove the punctuation '!', '.', ':' from a string `asking`

out = ''.join(c for c in asking if c not in ('!', '.', ':'))

out = ''.join(c for c in VAR_STR if c not in ('VAR_STR', 'VAR_STR', 'VAR_STR'))


use a list of values `[3,6]` to select rows from a pandas dataframe `df`'s column 'A'


Parse a file `sample.xml` using expat parsing in python 3


match zero-or-more instances of lower case alphabet characters in a string `f233op `


Convert hex string "deadbeef" to integer


encode unicode string '\xc5\xc4\xd6' to utf-8 code


solve for the least squares' solution of matrices `a` and `b`

np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))

np.linalg.solve(np.dot(VAR_STR.T, VAR_STR), np.dot(VAR_STR.T, VAR_STR))


create a file 'filename' with each tuple in the list `mylist` written to a line

open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))

open('VAR_STR', 'w').write('\n'.join('%s %s' % x for x in VAR_STR))


print numbers in list `list` with precision of 3 decimal places

print('[%s]' % ', '.join('%.3f' % val for val in list))

print('[%s]' % ', '.join('%.3f' % val for val in VAR_STR))


format print output of list of floats `l` to print only up to 3 decimal points


print a list of floating numbers `l` using string formatting

print([('%5.3f' % val) for val in VAR_STR])


Get a md5 hash from string `thecakeisalie`


replace string 'in.' with ' in. ' in dataframe `df` column 'a'

df['a'] = df['a'].str.replace('in.', ' in. ')

VAR_STR['VAR_STR'] = VAR_STR['VAR_STR'].str.replace('VAR_STR', ' in. ')


convert string `x'  to dictionary splitted by `=` using list comprehension


add a column 'new_col' to dataframe `df` for index in range

df['new_col'] = list(range(1, len(df) + 1))

VAR_STR['VAR_STR'] = list(range(1, len(VAR_STR) + 1))


apply logical operator 'AND' to all elements in list `a_list`


get a list of booleans `z` that shows wether the corresponding items in list `x` and `y` are equal

VAR_STR = [(i == j) for i, j in zip(VAR_STR, VAR_STR)]


create a list which indicates whether each element in `x` and `y` is identical

[(VAR_STR[i] == VAR_STR[i]) for i in range(len(VAR_STR))]


convert currency string `dollars` to decimal `cents_int`

cents_int = int(round(float(dollars.strip('$')) * 100))

VAR_STR = int(round(float(VAR_STR.strip('$')) * 100))


sort list `users` using values associated with key 'id' according to elements in list `order`


sort a python list of dictionaries `users` by a given list `order` of ids 'id' with the desired order


Get all indexes of a letter `e` from a string `word`

[index for index, letter in enumerate(word) if letter == 'e']

[index for index, letter in enumerate(VAR_STR) if letter == 'VAR_STR']


format parameters 'b' and 'a' into plcaeholders in string "{0}\\w{{2}}b{1}\\w{{2}}quarter"


def bufcount(filename):
    f = open(filename)
    lines = 0
    buf_size = (1024 * 1024)
    read_f = f.read
    buf = read_f(buf_size)
    while buf:
        lines += buf.count('\n')
        buf = read_f(buf_size)
    return lines

def bufcount(VAR_STR):
    f = open(VAR_STR)
    lines = 0
    buf_size = 1024 * 1024
    read_f = f.read
    buf = read_f(buf_size)
    while buf:
        lines += buf.count('\n')
        buf = read_f(buf_size)
    return lines


Determine the byte length of a utf-8 encoded string `s`


specify multiple positional arguments with argparse


delete every 8th column in a numpy array 'a'.

np.delete(a, list(range(0, a.shape[1], 8)), axis=1)

np.delete(VAR_STR, list(range(0, VAR_STR.shape[1], 8)), axis=1)


Replace repeated instances of a character '*' with a single instance in a string 'text'


replace repeated instances of "*" with a single instance of "*"


[i.partition('\t')[-1] for i in l if '\t' in i]

[i.partition('VAR_STR')[-1] for i in VAR_STR if 'VAR_STR' in i]


get two random records from model 'MyModel' in Django


get value of first child of xml node `name`


Convert a hex string `437c2123 ` according to ascii value.


Get all `a` tags where the text starts with value `some text` using regex


split string `str1` on one or more spaces with a regular expression


python split string based on regular expression


BeautifulSoup find all tags with attribute 'name' equal to 'description'


get the dot product of two one dimensional numpy arrays


multiplication of two 1-dimensional arrays  in numpy


insert a list `k` at the front of list `a`


insert elements of list `k` into list `a` at position `n`

VAR_STR = VAR_STR[:VAR_STR] + VAR_STR + VAR_STR[VAR_STR:]


get values from a dictionary `my_dict` whose key contains the string `Date`

[v for k, v in list(my_dict.items()) if 'Date' in k]

[v for k, v in list(VAR_STR.items()) if 'VAR_STR' in k]


Print variable `count` and variable `conv` with space string '    ' in between

print(str(VAR_STR) + '    ' + str(VAR_STR))


convert JSON string '2012-05-29T19:30:03.283Z' into a DateTime object using format '%Y-%m-%dT%H:%M:%S.%fZ'


convert list `data` into a string of its elements


sort list `lst` in descending order based on the second item of each tuple in it

lst.sort(key=lambda x: x[2], reverse=True)

VAR_STR.sort(key=lambda x: x[2], reverse=True)


Replace non-ASCII characters in string `text` with a single space


get all digits in a string `s` after a '[' character


create a list of tuples which contains number 9 and the number before it, for each occurrence of 9 in the list 'myList'

[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]

[(x, y) for x, y in zip(VAR_STR, VAR_STR[1:]) if y == 9]


remove all instances of [1, 1] from list `a`

VAR_STR[:] = [x for x in VAR_STR if x != [1, 1]]


remove all instances of `[1, 1]` from a list `a`


Convert nested list `x` into a flat list


get each value from a list of lists `a` using itertools


get the indices of tuples in list of tuples `L` where the first value is 53

[i for i, v in enumerate(L) if v[0] == 53]

[i for i, v in enumerate(VAR_STR) if v[0] == 53]


convert string '2011221' into a DateTime object using format '%Y%W%w'


Create a dictionary from string `e` separated by `-` and `,`

dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))

dict((k, int(v)) for k, v in (VAR_STR.split(' - ') for VAR_STR in s.split('VAR_STR'))
    )


insert directory './path/to/your/modules/' to current directory


Sort a list of strings 'words' such that items starting with 's' come first.

sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)

sorted(VAR_STR, key=lambda x: 'a' + x if x.startswith('VAR_STR') else 'b' + x)


execute a mv command `mv /home/somedir/subdir/* somedir/` in subprocess

subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)


How to use the mv command in Python with subprocess

subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)


use regex pattern '^12(?=.{4}$)' to remove digit 12 if followed by 4 other digits in column `c_contofficeID` of dataframe `df`


find all digits between two characters `\xab` and `\xbb`in a string `text`


convert utf-8 with bom string `s` to utf-8 with no bom `u`


convert unicode string '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0' to byte string


get a list of items from the list `some_list` that contain string 'abc'

matching = [s for s in some_list if 'abc' in s]

matching = [s for s in VAR_STR if 'VAR_STR' in s]


swap each pair of characters in string `s`

"""""".join([VAR_STR[x:x + 2][::-1] for x in range(0, len(VAR_STR), 2)])


django return a QuerySet list containing the values of field 'eng_name' in model `Employees`


sum elements at the same index of each list in list `lists`


writing items in list `thelist` to file `thefile`

for item in thelist:
    thefile.write(('%s\n' % item))

for item in VAR_STR:
    VAR_STR.write('%s\n' % item)


writing items in list `itemlist` to file `outfile`


replace all the nan values with 0 in a pandas dataframe `df`


convert a 1d `A` array to a 2d array `B`


update a list `l1` dictionaries with a key `count` and value from list `l2`

[dict(d, count=n) for d, n in zip(l1, l2)]

[dict(d, VAR_STR=n) for d, n in zip(VAR_STR, VAR_STR)]


merge rows from dataframe `df1` with rows from dataframe `df2` and calculate the mean for rows that have the same value of axis 1


remove the element in list `a` with index 1


remove the element in list `a` at index `index`


sort a dictionary `d` by length of its values and print as string

print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))

print(' '.join(sorted(VAR_STR, key=lambda k: len(VAR_STR[k]), reverse=True)))


Replace comma with dot in a string `original_string` using regex


plot data of column 'index' versus column 'A' of dataframe `monthly_mean` after resetting its index


set environment variable 'DEBUSSY' equal to 1


set environment variable 'DEBUSSY' to '1'


convert pandas group by object to multi-indexed dataframe with indices 'Name' and 'Destination'


decode unicode string `s` into a readable unicode literal


get a random key `country` and value `capital` form a dictionary `d`

country, capital = random.choice(list(d.items()))

VAR_STR, VAR_STR = random.choice(list(VAR_STR.items()))


zip file `pdffile` using its basename as directory name


call bash command 'tar c my_dir | md5sum' with pipe

subprocess.call('tar c my_dir | md5sum', shell=True)


trim whitespace (including tabs) in `s` on the left side


trim whitespace (including tabs) in `s` on the right side


trim whitespaces (including tabs) in string `s`


set color marker styles `--bo` in matplotlib


set circle markers on plot for individual points  defined in list   `[1,2,3,4,5,6,7,8,9,10]` created by range(10)

plt.plot(list(range(10)), linestyle='--', marker='o', color='b')


sort list `results` by keys value 'year'


sort array `arr` in ascending order by values of the 3rd column


sort rows of numpy matrix `arr` in ascending order according to all column values


Format a string `u'Andr\xc3\xa9'` that has unicode characters

"""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')

"""""".join(chr(ord(c)) for c in 'AndrÃ©')


convert a unicode 'Andr\xc3\xa9' to a string

"""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')

"""""".join(chr(ord(c)) for c in 'VAR_STR').decode('utf8')


remove white spaces from the end of string "    xyz     "


Convert string '03:55' into datetime.time object


generate all possible string permutations of each two elements in list `['hel', 'lo', 'bye']`

print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])

print([''.join(a) for a in combinations([VAR_STR], 2)])


print a list of integers `list_of_ints` using string formatting

print(', '.join(str(x) for x in list_of_ints))

print(', '.join(str(x) for x in VAR_STR))


un-escaping characters in a string with python


save current figure to file 'graph.png' with resolution of 1000 dpi


Print a emoji from a string `\\ud83d\\ude4f` having surrogate pairs


apply two different aggregating functions `mean` and `sum` to the same column `dummy` in pandas data frame `df`


map two lists `keys` and `values` into a dictionary

new_dict = {k: v for k, v in zip(keys, values)}

new_dict = {k: v for k, v in zip(VAR_STR, VAR_STR)}


dict((k, v) for k, v in zip(keys, values))

dict((k, v) for k, v in zip(VAR_STR, VAR_STR))


dict([(k, v) for k, v in zip(keys, values)])

dict([(k, v) for k, v in zip(VAR_STR, VAR_STR)])


get a list of substrings consisting of the first 5 characters of every string in list `buckets`


Rearrange the columns 'a','b','x','y' of pandas DataFrame `df` in mentioned sequence 'x' ,'y','a' ,'b'

VAR_STR = VAR_STR[['VAR_STR', 'VAR_STR', 'VAR_STR', 'VAR_STR']]


Get a list of all fields in class `User` that are marked `required`

[k for k, v in User._fields.items() if v.required]

[k for k, v in VAR_STR._fields.items() if v.VAR_STR]


create a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3'


Get rank of rows from highest to lowest of dataframe `df`, grouped by value in column `group`, according to value in column `value`


remove column by index `[:, 0:2]` in dataframe `df`


convert a list of hex byte strings `['BB', 'A7', 'F6', '9E']` to a list of hex integers


convert the elements of list `L` from hex byte strings to hex integers


Create a dictionary `d` from list `iterable`

d = dict(((key, value) for (key, value) in iterable))

VAR_STR = dict((key, value) for key, value in VAR_STR)


d = {key: value for (key, value) in iterable}

VAR_STR = {key: value for key, value in VAR_STR}


Create a dictionary `d` from list of key value pairs `iterable`


drop a single subcolumn 'a' in column 'col1' from a dataframe `df`


dropping all columns named 'a' from a multiindex 'df', across all level.


return list `result` of sum of elements of each list `b` in list of lists `a`

VAR_STR = [sum(VAR_STR) for VAR_STR in VAR_STR]


make a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)

ebar = plt.errorbar(x, y, yerr=err, ecolor='y')

VAR_STR = plt.errorbar(x, VAR_STR, yerr=err, ecolor='VAR_STR')


open a file `/home/user/test/wsservice/data.pkl` in binary write mode

output = open('/home/user/test/wsservice/data.pkl', 'wb')


compare two lists in python `a` and `b` and return matches


How can I compare two lists in python and return matches


sort a dictionary `a` by values that are list type

t = sorted(list(a.items()), key=lambda x: x[1])

t = sorted(list(VAR_STR.items()), key=lambda x: x[1])


Replace all non-alphanumeric characters in a string


find all possible sequences of elements in a list `[2, 3, 4]`


create a list by appending components from list `a` and reversed list `b` interchangeably

[value for pair in zip(a, b[::-1]) for value in pair]

[value for pair in zip(VAR_STR, VAR_STR[::-1]) for value in pair]


get http header of the key 'your-header-name' in flask


Create list `listy` containing 3 empty lists


convert datetime.date `dt` to utc timestamp

timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

timestamp = (VAR_STR - datetime(1970, 1, 1)).total_seconds()


find float number proceeding sub-string `par` in string `dir`


Get all the matches from a string `abcd` if it begins with a character `a`


get a relative path of file 'my_file' into variable `fn`

fn = os.path.join(os.path.dirname(__file__), 'my_file')

VAR_STR = os.path.join(os.path.dirname(__file__), 'VAR_STR')


Can I sort text by its numeric value in Python?

sorted(list(mydict.items()), key=lambda a: map(int, a[0].split('.')))


execute python code `myscript.py` in a virtualenv `/path/to/my/venv` from matlab


remove dictionary from list `a` if the value associated with its key 'link' is in list `b`

a = [x for x in a if x['link'] not in b]

VAR_STR = [x for x in VAR_STR if x['VAR_STR'] not in VAR_STR]


Convert a string of numbers `example_string` separated by `,` into a list of integers


Convert a string of numbers 'example_string' separated by comma into a list of numbers

[int(s) for s in example_string.split(',')]


remove newlines and whitespace from string `yourstring`


Get a list of pairs of key-value sorted by values in dictionary `data`

sorted(list(data.items()), key=lambda x: x[1])

sorted(list(VAR_STR.items()), key=lambda x: x[1])


sorted(list(data.items()), key=lambda x: x[1])


update all values associated with key `i` to string 'updated' if value `j` is not equal to 'None' in dictionary `d`

{i: 'updated' for i, j in list(d.items()) if j != 'None'}

{VAR_STR: 'VAR_STR' for VAR_STR, VAR_STR in list(VAR_STR.items()) if VAR_STR != 'VAR_STR'}


Filter a dictionary `d` to remove keys with value None and replace other values with 'updated'

dict((k, 'updated') for k, v in d.items() if v is None)

dict((k, 'VAR_STR') for k, v in VAR_STR.items() if v is None)


Filter a dictionary `d` to remove keys with value 'None' and replace other values with 'updated'

dict((k, 'updated') for k, v in d.items() if v != 'None')

dict((k, 'VAR_STR') for k, v in VAR_STR.items() if v != 'VAR_STR')


create a list `listofzeros` of `n` zeros


sort a list `s` by first and second attributes

s = sorted(s, key=lambda x: (x[1], x[2]))

VAR_STR = sorted(VAR_STR, key=lambda x: (x[1], x[2]))


sort a list of lists `s` by second and third element in each list.


sort dictionary of lists `myDict` by the third item in each list

sorted(list(myDict.items()), key=lambda e: e[1][2])

sorted(list(VAR_STR.items()), key=lambda e: e[1][2])


get the first element of each tuple in a list `rows`


get a list `res_list` of the first elements of each tuple in a list of tuples `rows`


append the first element of array `a` to array `a`


open a file 'bundled-resource.jpg' in the same directory as a python script

f = open(os.path.join(__location__, 'bundled-resource.jpg'))

f = open(os.path.join(__location__, 'VAR_STR'))


Set value for key `a` in dict `count` to `0` if key `a` does not exist or if value is `none`


serialise SqlAlchemy RowProxy object `row` to a json object

json.dumps([dict(list(row.items())) for row in rs])

json.dumps([dict(list(VAR_STR.items())) for VAR_STR in rs])


check if dictionary `L[0].f.items()` is in dictionary `a3.f.items()`


convert a python dictionary `d` to a list of tuples

[(v, k) for k, v in list(VAR_STR.items())]


convert dictionary of pairs `d` to a list of tuples


convert python 2 dictionary `a` to a list of tuples where the value is the first tuple element and the key is the second tuple element


convert a python dictionary 'a' to a list of tuples


[l[i:i + n] for i in range(0, len(l), n)]

[VAR_STR[i:i + VAR_STR] for i in range(0, len(VAR_STR), VAR_STR)]


split a list `l` into evenly sized chunks `n`


print 'here is your checkmark: ' plus unicode character u'\u2713'

print('here is your checkmark: ' + '\u2713')

print('here is your checkmark: ' + 'VAR_STR')


print unicode characters in a string `\u0420\u043e\u0441\u0441\u0438\u044f`


Initialize a list of empty lists `a` of size 3


remove letters from string `example_line` if the letter exist in list `bad_chars`

"""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]

"""""".join(dropwhile(lambda x: x in VAR_STR, VAR_STR[::-1]))[::-1]


get everything after last slash in a url stored in variable 'url'


Find the list in a list of lists `alkaline_earth_values` with the max value of the second element.

max(alkaline_earth_values, key=lambda x: x[1])


remove elements from list `centroids` the indexes of which are in array `index`

[element for i, element in enumerate(centroids) if i not in index]

[element for i, element in enumerate(VAR_STR) if i not in VAR_STR]


convert a list of dictionaries `listofdict into a dictionary of dictionaries

dict((d['name'], d) for d in listofdict)


sort a list `unsorted_list` based on another sorted list `presorted_list`


For each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.

[a[VAR_STR].append(VAR_STR[VAR_STR]) for VAR_STR in range(3)]


convert dictionary `dict` into a flat list

print([y for x in list(dict.items()) for y in x])

print([y for x in list(VAR_STR.items()) for y in x])


Convert a dictionary `dict` into a list with key and values as list items.

[y for x in list(dict.items()) for y in x]

[y for x in list(VAR_STR.items()) for y in x]


split a string 's' by space while ignoring spaces within square braces and quotes.


Sort dictionary `x` by value in ascending order


Sort dictionary `dict1` by value in ascending order


Sort dictionary `d` by value in descending order


Sort dictionary `d` by value in ascending order

sorted(list(d.items()), key=(lambda x: x[1]))

sorted(list(VAR_STR.items()), key=lambda x: x[1])


Fit Kmeans function to a one-dimensional array `x` by reshaping it to be a multidimensional array of single values


django create a foreign key column `user` and link it to table 'User'

user = models.ForeignKey('User', unique=True)

VAR_STR = models.ForeignKey('VAR_STR', unique=True)


write a list of strings `row` to csv object `csvwriter`


pass dictionary items `data` as keyword arguments in function `my_function`


merge the elements in a list `lst` sequentially

[''.join(seq) for seq in zip(lst, lst[1:])]

[''.join(seq) for seq in zip(VAR_STR, VAR_STR[1:])]


make matplotlib plot legend put marker in legend only once


switch keys and values in a dictionary `my_dict`

dict((v, k) for k, v in my_dict.items())

dict((v, k) for k, v in VAR_STR.items())


regular expression for validating string 'user' containing a sequence of characters ending with '-' followed by any number of digits.


Get a list comprehension in list of lists `X`

[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))]

[[VAR_STR[i][j] for j in range(len(VAR_STR[i]))] for i in range(len(VAR_STR))]


convert `ms` milliseconds to a datetime object


change a string of integers `x` separated by spaces to a list of int


convert a string of integers `x` separated by spaces to a list of integers

VAR_STR = [int(i) for i in VAR_STR.split()]


subprocess run command 'start command -flags arguments' through the shell

subprocess.call('start command -flags arguments', shell=True)


run command 'command -flags arguments &' on command line tools as separate processes

subprocess.call('command -flags arguments &', shell=True)


Selenium get the entire `driver` page text


regex matching 5-digit substrings not enclosed with digits in `s`


convert a list of strings `['1', '-1', '1']` to a list of numbers


concatenate items from list `parts` into a string starting from the second element


insert a character ',' into a string in front of '+' character in second part of the string


Use multiple groupby and agg operations `sum`, `count`, `std` for pandas data frame `df`


output data of the first 7 columns of Pandas dataframe


Display maximum output data of columns in dataframe `pandas` that will fit into the screen


sort list `the_list` by the length of string followed by alphabetical order

the_list.sort(key=lambda item: (-len(item), item))

VAR_STR.sort(key=lambda item: (-len(item), item))


convert list `a` from being consecutive sequences of tuples into a single sequence of elements


convert a flat list into a list of tuples of every two items in the list, in order


group a list of ints into a list of tuples of each 2 elements

my_new_list = zip(my_list[0::2], my_list[1::2])


Slice `url` with '&' as delimiter  to get  "http://www.domainname.com/page?CONTENT_ITEM_ID=1234" from url "http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3
"


convert python dictionary `your_data` to json array


retrieve arabic texts from string `my_string`


sort list `L` based on the value of variable 'resultType' for each object in list `L`


sort a list of objects `s` by a member variable 'resultType'


sort a list of objects 'somelist' where the object has member number variable `resultType`


with open('example.yaml', 'r') as stream:
    try:
        print((yaml.load(stream)))
    except yaml.YAMLError as exc:
        print(exc)

with open('VAR_STR', 'r') as stream:
    try:
        print(yaml.load(stream))
    except yaml.YAMLError as exc:
        print(exc)


with open('example.yaml') as stream:
    try:
        print((yaml.load(stream)))
    except yaml.YAMLError as exc:
        print(exc)

with open('VAR_STR') as stream:
    try:
        print(yaml.load(stream))
    except yaml.YAMLError as exc:
        print(exc)


split string `s` into float values and write sum to `total`

total = sum(float(item) for item in s.split(','))

VAR_STR = sum(float(item) for item in VAR_STR.split(','))


substitute occurrences of unicode regex pattern u'\\p{P}+' with empty string '' in string `text`

return re.sub('VAR_STR', 'VAR_STR', VAR_STR)


get the absolute path of a running python script


access value associated with key 'American' of key 'Apple' from dictionary `dict`


find rows with non zero values in a subset of columns where `df.dtypes` is not equal to `object` in pandas dataframe

df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]

df.loc[(df.loc[:, (df.dtypes != VAR_STR)] != 0).any(1)]


check if all elements in a tuple `(1, 6)` are in another `(1, 2, 3, 4, 5)`


Get a list `C` by subtracting values in one list `B` from corresponding values in another list `A`

VAR_STR = [(a - b) for a, b in zip(VAR_STR, VAR_STR)]


pull a value with key 'name' from a json object `item`


removing vowel characters 'aeiouAEIOU' from string `text`

"""""".join(c for c in text if c not in 'aeiouAEIOU')

"""""".join(c for c in VAR_STR if c not in 'VAR_STR')


get last element of string splitted by '\\' from list of strings `list_dirs`

[l.split('VAR_STR')[-1] for l in VAR_STR]


function to check if a string is a number


find all occurrences of regex pattern '(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)' in string `x`


Return rows of data associated with the maximum value of column 'Value' in dataframe `df`


Convert a datetime object `my_datetime` into readable format `%B %d, %Y`


Sort items in dictionary `d`  using the first part of the key after splitting the key

sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))

sorted(list(VAR_STR.items()), key=lambda name_num: (name_num[0].rsplit(None,
    1)[0], name_num[1]))


response = requests.put(url, data=json.dumps(data), headers=headers)

response = requests.put(VAR_STR, data=json.dumps(data), headers=headers)


build a dictionary containing the conversion of each list in list `[['two', 2], ['one', 1]]` to a key/value pair as its items


convert list `l` to dictionary having each two adjacent elements as key/value pair


create list `c` containing items from list `b` whose index is in list `index`


get geys of dictionary `my_dict` that contain any values from list `lst`

[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]

[key for key, value in list(VAR_STR.items()) if set(value).intersection(VAR_STR)]


get list of keys in dictionary `my_dict` whose values contain values from list `lst`

[key for item in lst for key, value in list(my_dict.items()) if item in value]

[key for item in VAR_STR for key, value in list(VAR_STR.items()) if item in value]


get first non-null value per each row from dataframe `df`


Update row values for a column `Season` using vectorized string operation in pandas


find all digits in string '6,7)' and put them to a list


check if  dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`

all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])

all(word in VAR_STR for word in [VAR_STR])


"""""".join([c for c in strs if c.isdigit()])

"""""".join([c for c in VAR_STR if c.isdigit()])


sort dictionary `tag_weight` in reverse order by values cast to integers

sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)

sorted(list(VAR_STR.items()), key=lambda x: int(x[1]), reverse=True)


sort list `mylist` of tuples by arbitrary key from list `order`

sorted(mylist, key=lambda x: order.index(x[1]))

sorted(VAR_STR, key=lambda x: VAR_STR.index(x[1]))


multiply values of dictionary `dict` with their respective values in dictionary `dict2`

dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)

VAR_STR((k, v * VAR_STR[k]) for k, v in list(dict1.items()) if k in VAR_STR)


insert directory 'libs' at the 0th index of current directory


download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext'


scroll to the bottom of a web page using selenium webdriver


scroll a to the bottom of a web page using selenium webdriver


append array of strings `['x', 'x', 'x']` into one string


Find all the items from a dictionary `D` if the key contains the string `Light`

[(k, v) for k, v in D.items() if 'Light' in k]

[(k, v) for k, v in VAR_STR.items() if 'VAR_STR' in k]


create a list `result` containing elements form list `list_a` if first element of list `list_a` is in list `list_b`

result = [x for x in list_a if x[0] in list_b]

VAR_STR = [x for x in VAR_STR if x[0] in VAR_STR]


transforming the string `s` into dictionary

dict(map(int, x.split(':')) for x in s.split(','))

dict(map(int, x.split(':')) for x in VAR_STR.split(','))


set UTC offset by 9 hrs ahead for date '2013/09/11 00:17'


Return a subplot axes positioned by the grid definition `1,1,1` using matpotlib


replace nan values in a pandas data frame with the average of columns

df.apply(lambda x: x.fillna(x.mean()), axis=0)


sort dictionary of dictionaries `dic` according to the key 'Fisher'

sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)

sorted(list(VAR_STR.items()), key=lambda x: x[1]['VAR_STR'], reverse=True)


set font size of axis legend of plot `plt` to 'xx-small'


Get a list of  words from a string `Hello world, my name is...James the 2nd!` removing punctuation

re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')


List all the files that doesn't contain the name `hello`


List all the files that matches the pattern `hello*.txt`


upload binary file `myfile.txt` with ftplib

ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))

ftp.storbinary('STOR myfile.txt', open('VAR_STR', 'rb'))


convert and escape string "\\xc3\\x85あ" to UTF-8 code


combine  dataframe `df1` and dataframe `df2` by index number

pd.merge(df1, df2, left_index=True, right_index=True, how='outer')

pd.merge(VAR_STR, VAR_STR, left_index=True, right_index=True, how='outer')


Combine two Pandas dataframes with the same index


replace parentheses and all data within it with empty string '' in column 'name' of dataframe `df`


delete items from list `my_list` if the item exist in list `to_dell`

my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]

VAR_STR = [[x for x in sublist if x not in to_del] for sublist in VAR_STR]


invoke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to it


filter lines from a text file 'textfile' which contain a word 'apple'

[line for line in open('textfile') if 'apple' in line]

[line for line in open('VAR_STR') if 'VAR_STR' in line]


Check if the value of the key "name" is "Test" in a list of dictionaries `label`

any(d['VAR_STR'] == 'VAR_STR' for d in VAR_STR)


get value in string `line` matched by regex pattern '\\bLOG_ADDR\\s+(\\S+)'


remove all null values from columns 'three', 'four' and 'five' of dataframe `df2`

df2.dropna(subset=['three', 'four', 'five'], how='all')

VAR_STR.dropna(subset=['VAR_STR', 'VAR_STR', 'VAR_STR'], how='all')


insert variables `(var1, var2, var3)` into sql statement 'INSERT INTO table VALUES (?, ?, ?)'

cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))


Execute a sql statement using variables `var1`, `var2` and `var3`

cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))

cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (VAR_STR, VAR_STR, VAR_STR))


How to use variables in SQL statement in Python?

cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))


Selenium `driver` click a hyperlink with the pattern "a[href^='javascript']"


Print string `t` with proper unicode representations


convert list `lst` of key, value pairs into a dictionary

dict([(e[0], int(e[1])) for e in VAR_STR])


Print a string `card` with string formatting


convert list of strings `str_list` into list of integers


convert a list with string `['1', '2', '3']` into list with integers


convert list with str into list with int


Return values for column `C` after group by on column `A` and `B` in dataframe `df`


Add header `('Cookie', 'cookiename=cookie value')` to mechanize browser `br`

br.addheaders = [('Cookie', 'cookiename=cookie value')]


execute a command `command ` in the terminal from a python script


attach debugger pdb to class `ForkedPdb`


drop all columns in dataframe `df` that holds a maximum value bigger than 0


concatenate lists `listone` and `listtwo`


iterate items in lists `listone` and `listtwo`

for item in itertools.chain(listone, listtwo):
    pass

for item in itertools.chain(VAR_STR, VAR_STR):
    pass


convert date string `s` in format pattern '%d/%m/%Y' into a timestamp


convert string '01/12/2011' to an integer timestamp


move the last item in list `a` to the beginning


Remove the string value `item` from a list of strings `my_sequence`

[item for item in my_sequence if item != 'item']

[VAR_STR for VAR_STR in VAR_STR if VAR_STR != 'VAR_STR']


print each first value from a list of tuples `mytuple` with string formatting

print(', ,'.join([str(i[0]) for i in mytuple]))

print(', ,'.join([str(i[0]) for i in VAR_STR]))


Serialize dictionary `data` and its keys to a JSON formatted string

json.dumps({str(k): v for k, v in data.items()})

json.dumps({str(k): v for k, v in VAR_STR.items()})


remove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into floats


insert spaces before capital letters in string `text`


Get all the sentences from a string `text` using regex


Regular expression in Python sentence extractor


convert a list 'a' to a dictionary where each even element represents the key to the dictionary, and the following odd element is the value

b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}

b = {VAR_STR[i]: VAR_STR[i + 1] for i in range(0, len(VAR_STR), 2)}


replace value 0 with 'Female' and value 1 with 'Male' in column 'sex' of dataframe `data`

data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)

VAR_STR['VAR_STR'].replace([0, 1], ['VAR_STR', 'VAR_STR'], inplace=True)


convert date string 'January 11, 2010'  into day of week

datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')

datetime.datetime.strptime('VAR_STR', '%B %d, %Y').strftime('%A')


datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')


check if key 'stackoverflow' and key 'google' are presented in dictionary `sites`


convert unicode text from list `elems` with index 0 to normal text 'utf-8'


Convert a datetime object `dt` to microtime

time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0

time.mktime(VAR_STR.timetuple()) + VAR_STR.microsecond / 1000000.0


check whether file "/path/to/file" exists

my_file = Path('/path/to/file')
if my_file.is_file():
    pass

my_file = Path('VAR_STR')
if my_file.is_file():
    pass


check whether a file "/etc/password.txt" exists


check whether a path "/does/not/exist" exists


check whether a file "/does/not/exist" exists


check whether a path "/etc/password.txt" exists


print line `line` from text file with 'utf-16-le' format


open a text file `data.txt` in io module with encoding `utf-16-le`

file = io.open('data.txt', 'r', encoding='utf-16-le')

file = io.open('VAR_STR', 'r', encoding='VAR_STR')


create a list with the sum of respective elements of the tuples of list `l`


count the number of elements in array `myArray`


BeautifulSoup select 'div' elements with an id attribute value ending with sub-string '_answer' in HTML parsed string `soup`


Get Last Day of the second month in 2002


Get Last Day of the second month in 2100


Get Last Day of the month `month` in year `year`


Get Last Day of the second month in year 2012


Get Last Day of the first month in year 2000

(datetime.date(2000, 2, 1) - datetime.timedelta(days=1))


print the string `Total score for`, the value of the variable `name`, the string `is` and the value of the variable `score` in one print call.

print(('Total score for', name, 'is', score))

print(('VAR_STR', VAR_STR, 'VAR_STR', VAR_STR))


print multiple arguments 'name' and 'score'.

print('Total score for {} is {}'.format(name, score))

print('Total score for {} is {}'.format(VAR_STR, VAR_STR))


print a string using multiple strings `name` and `score`

print('Total score for %s is %s  ' % (name, score))

print('Total score for %s is %s  ' % (VAR_STR, VAR_STR))


print string including multiple variables `name` and `score`

print(('Total score for', VAR_STR, 'is', VAR_STR))


limit float 13.9499999 to two decimal points


limit float 3.14159 to two decimal points


limit float 13.949999999999999 to two decimal points


sort list of strings in list `the_list` by integer suffix

sorted(the_list, key=lambda k: int(k.split('_')[1]))

sorted(VAR_STR, key=lambda k: int(k.split('_')[1]))


sort list of strings `the_list` by integer suffix before "_"

sorted(the_list, key=lambda x: int(x.split('_')[1]))

sorted(VAR_STR, key=lambda x: int(x.split('VAR_STR')[1]))


pass a list of parameters `((1, 2, 3),) to sql queue 'SELECT * FROM table WHERE column IN %s;'

cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))


find indexes of all occurrences of a substring `tt` in a string `ttt`

[m.start() for m in re.finditer('(?=tt)', 'ttt')]

[m.start() for m in re.finditer('(?=tt)', 'VAR_STR')]


find all occurrences of a substring in a string

[m.start() for m in re.finditer('test', 'test test test test')]


join Numpy array `b` with Numpy array 'a' along axis 0

VAR_STR = np.concatenate((VAR_STR, VAR_STR), axis=0)


select multiple ranges of columns 1-10, 15, 17, and 50-100 in pandas dataframe `df`


fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4

dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)

dict((k, v) for k, v in VAR_STR.items() if 2 < k < 4)


fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4

dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)

dict((k, v) for k, v in VAR_STR.items() if k > 2 and k < 4)


concatenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string


check if string `the_string` contains any upper or lower-case ASCII letters


get alpha value `alpha` of a png image `img`


save a numpy array `image_array` as an image 'outfile.jpg'


delete the last column of numpy array `a` and assign resulting array to `b`


Convert float 24322.34 to comma-separated string


os.system('ulimit -s unlimited; some_executable')


assign values to two variables, `var1` and `var2` from user input response to `'Enter two numbers here: ` split on whitespace

var1, var2 = input('Enter two numbers here: ').split()

VAR_STR, VAR_STR = input('Enter two numbers here: ').split()


get canonical path of the filename `path`


fill missing value in one column 'Cat1' with the value of another column 'Cat2'


request URI '<MY_URI>' and pass authorization token 'TOK:<MY_TOKEN>' to the header

r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})

r = requests.get('VAR_STR', headers={'Authorization': 'VAR_STR'})


Extract values not equal to 0 from numpy array `a`


print a string `s` by splitting with comma `,`


Create list  by splitting string `mystring` using "," as delimiter


remove periods inbetween capital letters that aren't immediately preceeded by word character(s) in a string `s` using regular expressions


Construct an array with data type float32 `a` from data in binary file 'filename'

a = numpy.fromfile('filename', dtype=numpy.float32)

VAR_STR = numpy.fromfile('VAR_STR', dtype=numpy.float32)


How to get the length of words in a sentence?


get a string `randomkey123xyz987` between two substrings in a string `api('randomkey123xyz987', 'key', 'text')` using regex

re.findall("api\\('(.*?)'", "api('randomkey123xyz987', 'key', 'text')")


create a list of aggregation of each element from list `l2` to all elements of list `l1`

[(x + y) for x in VAR_STR for y in VAR_STR]


get date from dataframe `df` column 'dates' to column 'just_date'


sort a list `your_list` of class objects by their values for the attribute `anniversary_score`


sort list `your_list` by the `anniversary_score` attribute of each object


split string 'a b.c' on space " " and dot character "."


count number of rows in a group `key_columns` in pandas groupby object `df`


delete every non `utf-8` characters from a string `line`

line = line.decode('utf-8', 'ignore').encode('utf-8')

VAR_STR = VAR_STR.decode('VAR_STR', 'ignore').encode('VAR_STR')


lowercase a python dataframe string in column 'x' if it has missing values in dataframe `df`


swap values in a tuple/list inside a list `mylist`


Swap values in a tuple/list in list `mylist`


Set index equal to field 'TRX_DATE' in dataframe `df`


change figure size to 3 by 4 in matplotlib


add column `d` to index of dataframe `df`


create a regular expression that matches the pattern '^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)' over multiple lines of text


regular expression "^(.+)\\n((?:\\n.+)+)" matching a multiline block of text


get equivalent week number from a date `2010/6/16` using  isocalendar


format floating point number  `TotalAmount` to be rounded off to two decimal places and have a comma thousands' seperator

print('Total cost is: ${:,.2f}'.format(TotalAmount))

print('Total cost is: ${:,.2f}'.format(VAR_STR))


split string 'abcdefg' into a list of characters


set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata`


replace a string `Abc` in case sensitive way using maketrans


get a list of values with key 'key' from a list of dictionaries `l`

[d['VAR_STR'] for d in VAR_STR if 'VAR_STR' in d]


get a list of values for key 'key' from a list of dictionaries `l`


get a list of values for key "key" from a list of dictionaries in `l`


change the font size on plot `matplotlib` to 22


replace comma in string `s` with empty string ''

VAR_STR = VAR_STR.replace(',', 'VAR_STR')


get the count of each unique value in column `Country` of dataframe `df` and store in column `Sum of Accidents`


OrderedDict(sorted(list(d.items()), key=(lambda t: t[0])))

OrderedDict(sorted(list(VAR_STR.items()), key=lambda t: t[0]))


get dictionary with max value of key 'size' in list of dicts `ld`

max(VAR_STR, key=lambda d: d['VAR_STR'])


create a dictionary containing each string in list `my_list` split by '=' as a key/value pairs

print(dict([s.split('=') for s in my_list]))

print(dict([s.split('VAR_STR') for s in VAR_STR]))


remove all values within one list `[2, 3, 7]` from another list `a`

[x for x in VAR_STR if x not in [VAR_STR]]


remove all duplicates from a list of sets `L`

list(set(frozenset(item) for item in L))

list(set(frozenset(item) for item in VAR_STR))


remove duplicates from a list of sets 'L'

[set(item) for item in set(frozenset(item) for item in L)]

[set(item) for item in set(frozenset(item) for item in VAR_STR)]


Concatenate elements of a list 'x' of multiple integers to a single integer

sum(d * 10 ** i for i, d in enumerate(x[::-1]))

sum(d * 10 ** i for i, d in enumerate(VAR_STR[::-1]))


convert a list of integers into a single integer


create dict of squared int values in range of 100


get complete path of a module named `os`


get current RAM usage of current program

pid = os.getpid()
py = psutil.Process(pid)
memoryUse = (py.memory_info()[0] / (2.0 ** 30))

pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0] / 2.0 ** 30


given list `to_reverse`, reverse the all sublists and the list itself

[sublist[::-1] for sublist in to_reverse[::-1]]

[sublist[::-1] for sublist in VAR_STR[::-1]]


extract table data from table `rows` using beautifulsoup

[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]

[[td.findNext(text=True) for td in tr.findAll('td')] for tr in VAR_STR]


find element `a` that contains string "TEXT A" in file `root`

e = root.xpath('.//a[contains(text(),"TEXT A")]')

e = VAR_STR.xpath('.//a[contains(text(),"TEXT A")]')


Find the`a` tag in html `root` which starts with the text `TEXT A`  and assign it to `e`

e = root.xpath('.//a[starts-with(text(),"TEXT A")]')

VAR_STR = VAR_STR.xpath('.//a[starts-with(text(),"TEXT A")]')


find the element that holds string 'TEXT A' in file `root`

e = VAR_STR.xpath('.//a[text()="TEXT A"]')


round number 32.268907563 up to 3 decimal points


round number `value` up to `significantDigit` decimal places


round number 1.0005 up to 3 decimal places


round number 2.0005 up to 3 decimal places


round number 3.0005 up to 3 decimal places


round number 4.0005 up to 3 decimal places


round number 8.005 up to 2 decimal places


round number 7.005 up to 2 decimal places


round number 6.005 up to 2 decimal places


round number 1.005 up to 2 decimal places


Divide elements in list `a` from elements at the same index in list `b`

[(x / y) for x, y in zip(VAR_STR, VAR_STR)]


Unpack each value in list `x` to its placeholder '%' in string '%.2f'

""", """.join(['VAR_STR'] * len(VAR_STR))


delete all columns in  DataFrame `df` that do not hold a non-zero value in its records

VAR_STR.loc[:, ((VAR_STR != 0).any(axis=0))]


Delete an element `key` from a dictionary `d`


Delete an element 0 from a dictionary `a`

{i: VAR_STR[i] for i in VAR_STR if i != 0}


Delete an element "hello" from a dictionary `lol`


Delete an element with key `key` dictionary `r`


python pandas: apply a function with arguments to a series

my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)


find element by css selector "input[onclick*='1 Bedroom Deluxe']"


get  value at index `[2, 0]` in dataframe `df`


check if the third element of all the lists in a list "items" is equal to zero.


Find all the lists from a lists of list 'items' if third element in all sub-lists is '0'


find all substrings in `mystring` beginning and ending with square brackets


VAR_STR = numpy.delete(VAR_STR, 2, axis=1)


VAR_STR = numpy.delete(VAR_STR, 0, axis=0)


request URL `url` using http header `{'referer': my_referer}`


get the widget which has currently the focus in tkinter instance `window2`

print(('focus object class:', window2.focus_get().__class__))

print(('focus object class:', VAR_STR.focus_get().__class__))


What is the best way to sort list with custom sorting parameters in Python?

li1.sort(key=lambda x: not x.startswith('b.'))


get user input using message 'Enter name here: ' and insert it to the first placeholder in string 'Hello, {0}, how do you do?'

print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))

print('VAR_STR'.format(input('Enter name here: ')))


Get all texts and tags from a tag `strong` from etree tag `some_tag` using lxml


get modification time of file `filename`


print(('last modified: %s' % time.ctime(os.path.getmtime(file))))

print('last modified: %s' % time.ctime(os.path.getmtime(VAR_STR)))


print(('created: %s' % time.ctime(os.path.getctime(file))))

print('created: %s' % time.ctime(os.path.getctime(VAR_STR)))


get the creation time of file `path_to_file`


generate a string of numbers separated by comma which is divisible by `4` with remainder `1` or `2`.

""",""".join(str(i) for i in range(100) if i % 4 in (1, 2))


remove first directory from path '/First/Second/Third/Fourth/Fifth'


convert nested list of lists `[['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]` into a list of tuples

list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))


print a digit `your_number` with exactly 2 digits after decimal


get biggest 3 values from each column of the pandas dataframe `data`


replace periods `.` that are not followed by periods or spaces with a period and a space `. `


convert hex string '0xdeadbeef' to decimal


convert hex string 'deadbeef' to decimal


Strip all non-ASCII characters from a unicode string, `\xa3\u20ac\xa3\u20ac`


Get all non-ascii characters in a unicode string `\xa3100 is worth more than \u20ac100`

print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))


removing duplicate characters from a string variable "foo"


convert a list of characters `['a', 'b', 'c', 'd']` into a string


join elements of each tuple in list `a` into one string


join items of each tuple in list of tuples `a` into a list of strings


split string "jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false," on the first occurrence of delimiter '='

"""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,""".split('=', 1)


get the middle two characters of a string 'state' in a pandas dataframe `df`

df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1])

VAR_STR['VAR_STR'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1])


join multiple dataframes `d1`, `d2`, and `d3` on column 'name'


How to sort a dictionary in python by value when the value is a list and I want to sort it by the first index of that list

sorted(list(data.items()), key=lambda x: x[1][0])


sort query set by number of characters in a field `length` in django model `MyModel`


read a ragged csv file `D:/Temp/tt.csv` using `names` parameter in pandas


Concatenating two one-dimensional NumPy arrays 'a' and 'b'.


create a regular expression object with the pattern '\xe2\x80\x93'


SQLAlchemy select records of columns of table `my_table` in addition to current date column


change NaN values in dataframe `df` using preceding values in the frame


counting the number of true booleans in a python list `[True, True, False, False, False, True]`

sum([True, True, False, False, False, True])


replacing  '\u200b' with '*' in a string  using regular expressions


display a grayscale image from array of pixels `imageArray`


unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`

pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')

pd.melt(VAR_STR, id_vars=['farm', 'fruit'], var_name='VAR_STR', value_name='VAR_STR')


add unicode string '1' to UTF-8 decoded string '\xc2\xa3'


convert unicode string `s` into string literals


Initialize a list of empty lists `x` of size 3


count the number of items in a generator/iterator `it`


convert nested list 'Cards' into a flat list

[a for c in Cards for b in c for a in b]

[a for c in VAR_STR for b in c for a in b]


remove specific elements in a numpy array `a`


get a list of all items in list `j` with values greater than `5`


merge dictionaries form array `dicts` in a single expression

dict((k, v) for d in dicts for k, v in list(d.items()))

dict((k, v) for d in VAR_STR for k, v in list(d.items()))


decode url-encoded string `some_string` to its character equivalents


decode a double URL encoded string
'FireShot3%2B%25282%2529.png' to
'FireShot3+(2).png'


join list of numbers `[1,2,3,4] ` to string of numbers.


start a new thread for `myfunction` with parameters 'MyStringHere' and 1


python sum of ascii values of all characters in a string `string`


create variable key/value pairs with argparse


convert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary

dict(zip(list(range(1, 5)), list(range(7, 11))))


create a list of integers between 2 values `11` and `17`


argparse associate zero or more arguments with flag 'file'


print a character that has unicode value `\u25b2`


set every two-stride far element to -1 starting from second element in array `a`


Get an item from a list of dictionary `lst` which has maximum value in the key `score` using lambda function

max(VAR_STR, key=lambda x: x['VAR_STR'])


SQLAlchemy count the number of rows with distinct values in column `name` of table `Tag`


get a list of items form nested list `li` where third element of each item contains string 'ar'

[x for x in VAR_STR if 'VAR_STR' in x[2]]


get index of character 'b' in list '['a', 'b']'


VAR_STR = VAR_STR.dropna(axis=1, how='all')


Log info message 'Log message' with attributes `{'app_name': 'myapp'}`

logging.info('Log message', extra={'app_name': 'myapp'})


Merge column  'word' in dataframe `df2` with column 'word' on dataframe `df1`


get the maximum of 'salary' and 'bonus' values in a dictionary

print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))

print(max(d, key=lambda x: (d[x]['VAR_STR'], d[x]['VAR_STR'])))


match blank lines in `s` with regular expressions


replace carriage return in string `somestring` with empty string ''


sort a list `L` by number after second '.'

print(sorted(L, key=lambda x: int(x.split('.')[2])))

print(sorted(VAR_STR, key=lambda x: int(x.split('VAR_STR')[2])))


Filter duplicate entries w.r.t. value in 'id' from a list of dictionaries 'L'

list(dict((x['id'], x) for x in L).values())

list(dict((x['VAR_STR'], x) for x in VAR_STR).values())


Copy list `old_list` and name it `new_list`


append string 'str' at the beginning of each value in column 'col' of dataframe `df`

df['col'] = 'str' + df['col'].astype(str)

VAR_STR['VAR_STR'] = 'VAR_STR' + VAR_STR['VAR_STR'].astype(VAR_STR)


BeautifulSoup find a tag whose id ends with string 'para'


select `div` tags whose `id`s begin with `value_xxx_c_1_f_8_a_`


match string 'this is my string' with regex '\\b(this|string)\\b'
then replace it with regex '<markup>\\1</markup>'

re.sub('\\b(this|string)\\b', '<markup>\\1</markup>', 'this is my string')


replace backslashes in string `result` with empty string ''

VAR_STR = VAR_STR.replace('\\', 'VAR_STR')


separate each character in string `s` by '-'


concatenate '-' in between characters of string `str`


cartesian product of `x` and `y` array points into single array of 2d points


remove index 2 element from a list `my_list`


Encode each value to 'UTF8' in the list `EmployeeList`

[x.encode('UTF8') for x in EmployeeList]


get the sum of each second value from a list of tuple `structure`


send data 'HTTP/1.0 200 OK\r\n\r\n' to socket `connection`


create a slice object using string `string_slice`

slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])

slice(*[(int(i.strip()) if i else None) for i in VAR_STR.split(':')])


append a pandas series `b` to the series `a` and get a continuous index


simple way to append a pandas series `a` and `b` with same index


split unicode string "раз два три" into words


change flask security register url to `/create_account`


open the login site 'http://somesite.com/adminpanel/index.php' in the browser


insert row into mysql database with column 'column1' set to the value `value`

cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,))

cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (VAR_STR,))


check if any item from list `b` is in list `a`

print(any(x in VAR_STR for x in VAR_STR))


un-escape a backslash-escaped string in `Hello,\\nworld!`


substitute two or more whitespace characters with character '|' in string `line`


create a list containing elements from list `list` that are predicate to function `f`


Make a scatter plot using unpacked values of list `li`


make a list of integers from 0 to `5` where each second element is a duplicate of the previous element

print([u for v in [[i, i] for i in range(5)] for u in v])


create a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`


create a list of integers from 1 to 5 with each value duplicated


convert a beautiful soup html `soup` to text


calculate the mean of columns with same name in dataframe `df`


create a list where each element is a dictionary with keys 'key1' and 'key2' and values corresponding to each value in the lists referenced by keys 'key1' and 'key2' in dictionary `d`

[{'VAR_STR': a, 'VAR_STR': b} for a, b in zip(VAR_STR['VAR_STR'], VAR_STR['VAR_STR'])]


Split dictionary of lists into list of dictionaries

map(dict, zip(*[[(k, v) for v in value] for k, value in list(d.items())]))


build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}`

ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")


combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary


pandas: change all the values of a column 'Date' into "int(str(x)[-4:])"

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))

df['VAR_STR'] = df['VAR_STR'].apply(lambda x: int(str(x)[-4:]))


format number 1000000000.0 using latex notation


randomly switch letters' cases in string `s`

"""""".join(x.upper() if random.randint(0, 1) else x for x in s)

"""""".join(x.upper() if random.randint(0, 1) else x for x in VAR_STR)


convert the argument `date` with string formatting in logging


Log message of level 'info' with value of `date` in the message


Do group by on `cluster` column in `df` and get its mean


sort list `strings` in alphabetical order based on the letter after percent character `%` in each element

strings.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))

VAR_STR.sort(key=lambda str: re.sub('.*%(.).*', '\\1', str))


sort a list of strings `strings` based on regex match

strings.sort(key=lambda str: re.sub('.*%', '', str))

VAR_STR.sort(key=lambda str: re.sub('.*%', '', str))


split string "This is a string" into words that do not contain whitespaces


split string "This     is a     string" into words that does not contain whitespaces


merge a pandas data frame `distancesDF` and column `dates` in pandas data frame `datesDF` into single


convert a list `my_list` into string with values separated by spaces


generate a list of all unique pairs of integers in `range(9)`


Split a string `text` with comma, question mark or exclamation by non-consuming regex using look-behind


Subtract the mean of each row in dataframe `df` from the corresponding row's elements


replace extension '.txt' in basename '/home/user/somefile.txt' with extension '.jpg'


find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's'


try:
    return int(s)
except ValueError:
    return float(s)

try:
    return int(VAR_STR)
except ValueError:
    return float(VAR_STR)


convert a list `L` of ascii values to a string


sort list `['10', '3', '2']` in ascending order based on the integer value of its elements


sorted(l, key=lambda x: x.replace('0', 'Z'))

sorted(VAR_STR, key=lambda x: x.replace('0', 'Z'))


strip a string `line` of all carriage returns and newlines


remove white space padding around a saved image `test.png` in matplotlib


execute a jar file 'Blender.jar' using subprocess


Find next sibling element in Python Selenium?


zip keys with individual values in lists `k` and `v`

[dict(zip(VAR_STR, x)) for x in VAR_STR]


read pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`

df = pd.read_csv('comma.csv', quotechar="'")

df = pd.read_csv('VAR_STR', quotechar='VAR_STR')


sort list of lists `L` by the second item in each list


extract dictionary values by key 'Feature3' from data frame `df`

feature3 = [d.get('Feature3') for d in df.dic]

feature3 = [d.get('VAR_STR') for d in VAR_STR.dic]


find the real user home directory using python


drop rows whose index value in list `[1, 3]` in dataframe `df`


extract the 2nd elements from a list of tuples


find the first letter of each element in string `input`

output = ''.join(item[0].upper() for item in input.split())

output = ''.join(item[0].upper() for item in VAR_STR.split())


replace percent-encoded code in request `f` to their single-character equivalent

f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))

VAR_STR = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.
    urlencode(params)))


call base class's __init__ method from the child class `ChildClass`


extract only alphabetic characters from a string `your string`

""" """.join(re.split('[^a-zA-Z]*', 'your string'))


Extract only characters from a string as a list


Convert binary string to list of integers using Python

[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]


find maximum with lookahead = 4 in a list `arr`

[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]

[max(abs(x) for x in VAR_STR[i:i + 4]) for i in range(0, len(VAR_STR), 4)]


replace single quote character in string "didn't" with empty string ''


Find a max value of the key `count` in a nested dictionary `d`

max(VAR_STR, key=lambda x: VAR_STR[x]['VAR_STR'])


Get a list of tuples with multiple iterators using list comprehension

[(i, j) for i in range(1, 3) for j in range(1, 5)]


remove all characters from string `stri` upto character 'I'


insert string `foo` at position `0` of list `list`


get the text of multiple elements found by xpath "//*[@type='submit']/@value"


find all the values in attribute `value` for the tags whose `type` attribute is `submit` in selenium


converting string '(1,2,3,4)' to a tuple


store data frame `df` to file `file_name` using pandas, python


extract all the values of a specific key named 'values' from a list of dictionaries

results = [item['value'] for item in test_data]


convert a date string `s` to a datetime object


Get only first element in each of the innermost of the multidimensional list `listD`

[[[x[0]] for x in listD[i]] for i in range(len(listD))]

[[[x[0]] for x in VAR_STR[i]] for i in range(len(VAR_STR))]


print a floating point number 2.345e-67 without any truncation


remove duplicate characters from string 'ffffffbbbbbbbqqq'


split string "a;bcd,ef g" on delimiters ';' and ','

"""VAR_STR""".replace('VAR_STR', ' ').replace('VAR_STR', ' ').split()


extract all rows from dataframe `data` where the value of column 'Value' is True


split string `s` into strings of repeating elements

print([a for a, b in re.findall('((\\w)\\2*)', s)])

print([a for a, b in re.findall('((\\w)\\2*)', VAR_STR)])


Trimming a string "          Hello        "


left trimming "\n\r" from string `myString`


right trimming "\n\t" from string `myString`


read csv file 'my_file.csv' into numpy array

my_data = genfromtxt('my_file.csv', delimiter=',')

my_data = genfromtxt('VAR_STR', delimiter=',')


df = pd.read_csv('myfile.csv', sep=',', header=None)

df = pd.read_csv('VAR_STR', sep=',', header=None)


multiply column 'A' and column 'B' by column 'C' in datafram `df`


Normalize string `str` from 'cp1252' code to 'utf-8' code


Iterating over a dictionary `d` using for loops

for key, value in VAR_STR.items():
    pass


for (key, value) in list(d.items()):
    pass

for key, value in list(VAR_STR.items()):
    pass


Iterating key and items over dictionary `d`

for (letter, number) in list(d.items()):
    pass

for letter, number in list(VAR_STR.items()):
    pass


for k, v in list(VAR_STR.items()):
    pass


get keys and items of dictionary `d` as a list


Create 2D numpy array from the data provided in 'somefile.csv' with each row in the file having same number of values

X = numpy.loadtxt('somefile.csv', delimiter=',')

X = numpy.loadtxt('VAR_STR', delimiter=',')


control the keyboard and mouse with dogtail in linux


sort datetime objects `birthdays` by `month` and `day`

birthdays.sort(key=lambda d: (d.month, d.day))

VAR_STR.sort(key=lambda d: (d.VAR_STR, d.VAR_STR))


remove trailing newline in string "test string\n"


remove trailing newline in string 'test string \n\n'


remove newline in string `s` on the right side


remove newline in string `s` on the left side


remove newline in string 'Windows EOL\r\n' on the right side


remove newline in string 'Unix EOL\n' on the right side


remove newline in string "Hello\n\n\n" on the right side


split string `text` by the occurrences of regex pattern '(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)'


split a string `s` by ';' and convert to a dictionary

dict(item.split('=') for item in s.split(';'))

dict(item.split('=') for item in VAR_STR.split('VAR_STR'))


create a list where each element is a value of the key 'Name' for each dictionary `d` in the list `thisismylist`

[VAR_STR['VAR_STR'] for VAR_STR in VAR_STR]


create a list of tuples with the values of keys 'Name' and 'Age' from each dictionary `d` in the list `thisismylist`

[(d['Name'], d['Age']) for d in thisismylist]

[(VAR_STR['VAR_STR'], VAR_STR['VAR_STR']) for VAR_STR in VAR_STR]


Reverse key-value pairs in a dictionary `map`

dict((v, k) for k, v in VAR_STR.items())


assign value in `group` dynamically to class property `attr`


sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))

sorted(VAR_STR, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))


test if either of strings `a` or `b` are members of the set of strings, `['b', 'a', 'foo', 'bar']`

set(['VAR_STR', 'VAR_STR']).issubset(['VAR_STR', 'VAR_STR', 'foo', 'bar'])


Check if all the values in a list `['a', 'b']` are present in another list `['b', 'a', 'foo', 'bar']`

all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])


format float `3.5e+20`  to `$3.5 \\times 10^{20}$` and set as title of matplotlib plot `ax`


set text color as `red` and background color as `#A3C1DA` in qpushbutton

setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')


convert an rgb image 'messi5.jpg' into grayscale `img`


create list `levels` containing 3 empty dictionaries


parse string '01-Jan-1995' into a datetime object using format '%d-%b-%Y'


Convert integer elements in list `wordids` to strings


get a list `cleaned` that contains all non-empty elements in list `your_list`


sorting the lists in list of lists `data`


remove identical items from list `my_list` and sort it alphabetically


convert a list of lists `a` into list of tuples of appropriate elements form nested lists


converting hex string `s` to its integer representations


create pandas data frame `df` from txt file `filename.txt` with column `Region Name` and separator `;`

df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])

VAR_STR = pd.read_csv('VAR_STR', sep='VAR_STR', names=['VAR_STR'])


get a list of all the duplicate items in dataframe `df` using pandas

pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)

pd.concat(g for _, g in VAR_STR.groupby('ID') if len(g) > 1)


sort objects in model `Profile` based on Theirs `reputation` attribute

sorted(Profile.objects.all(), key=lambda p: p.reputation)

sorted(VAR_STR.objects.all(), key=lambda p: p.VAR_STR)


for a dictionary `a`, set default value for key `somekey` as list and append value `bob`  in that key


replace white spaces in string '  a\n b\n c\nd  e' with empty string ''


remove white spaces from all the lines using a regular expression in string 'a\n b\n c'


sort dataframe `df` based on column 'b' in ascending and column 'c' in descending

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

VAR_STR.sort_values(['VAR_STR', 'VAR_STR'], ascending=[True, False], inplace=True)


sort dataframe `df` based on column 'a' in ascending and column 'b' in descending

df.sort_values(['a', 'b'], ascending=[True, False])

VAR_STR.sort_values(['VAR_STR', 'VAR_STR'], ascending=[True, False])


sort a pandas data frame with column `a` in ascending and `b` in descending order

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

df1.sort(['VAR_STR', 'VAR_STR'], ascending=[True, False], inplace=True)


sort a pandas data frame by column `a` in ascending, and by column `b` in descending order

df.sort(['a', 'b'], ascending=[True, False])

df.sort(['VAR_STR', 'VAR_STR'], ascending=[True, False])


create a symlink directory `D:\\testdirLink` for directory `D:\\testdir` with unicode support using ctypes library


Sort a list of dictionaries `mylist` by keys "weight" and "factor"


ordering a list of dictionaries `mylist` by elements 'weight' and 'factor'

mylist.sort(key=lambda d: (d['weight'], d['factor']))

VAR_STR.sort(key=lambda d: (d['VAR_STR'], d['VAR_STR']))


convert tuple elements in list `[(1,2),(3,4),(5,6),]` into lists


convert list of tuples to multiple lists in Python


derive the week start for the given week number and year ‘2011, 4, 0’

datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')


python selenium click on button '.button.c_button.s_button'


read CSV file 'my.csv' into a dataframe `df` with datatype of float for column 'my_column' considering character 'n/a' as NaN value

df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])

VAR_STR = pd.read_csv('VAR_STR', dtype={'VAR_STR': np.float64}, na_values=['VAR_STR'])


convert nan values to ‘n/a’ while reading rows from a csv `read_csv` with pandas

df = pd.read_csv('my.csv', na_values=['n/a'])

df = pd.VAR_STR('my.csv', na_values=['n/a'])


get indexes of all true boolean values from a list `bool_list`

[i for i, elem in enumerate(bool_list, 1) if elem]

[i for i, elem in enumerate(VAR_STR, 1) if elem]


get a list `no_integers` of all the items in list `mylist` that are not of type `int`

no_integers = [x for x in mylist if not isinstance(x, int)]

VAR_STR = [x for x in VAR_STR if not isinstance(x, VAR_STR)]


concatenating values in `list1` to a string


concatenating values in list `L` to a string, separate by space


concatenating values in list `L` to a string

makeitastring = ''.join(map(str, VAR_STR))


find consecutive segments from a column 'A' in a pandas data frame 'df'


place '\' infront of each non-letter char in string `line`


sort a list of tuples `my_list` by second parameter in the tuple


execute a file './abc.py' with arguments `arg1` and `arg2` in python shell


find the string matches within parenthesis from a string `s` using regex


decode the string 'stringnamehere'  to UTF-8


convert string `apple` from iso-8859-1/latin1 to utf-8


add key "item3" and value "3" to dictionary `default_data `


add key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`

default_data.update({'item4': 4, 'item5': 5, })

VAR_STR.update({'VAR_STR': 4, 'VAR_STR': 5})


split strings in list `l` on the first occurring tab `\t` and enter only the first resulting substring in a new list

[i.split('VAR_STR', 1)[0] for i in VAR_STR]


Split each string in list `myList` on the tab character

myList = [i.split('\t')[0] for i in myList]

VAR_STR = [i.split('\t')[0] for i in VAR_STR]


search for occurrences of regex pattern `pattern` in string `url`


convert all of the items in a list `lst` to float


encode string `data` using hex 'hex' encoding


Return the decimal value for each hex character in data `data`

print(' '.join([str(ord(a)) for a in data]))

print(' '.join([str(ord(a)) for a in VAR_STR]))


encode value of key `City` in dictionary `data` as `ascii`, ignoring non-ascii characters


Get all matching patterns 'a.*?a' from a string 'a 1 a 2 a 3 a 4 a'.


select all rows in dataframe `df` where the values of column 'columnX' is bigger than or equal to `x` and smaller than or equal to `y`

df[(x <= df['columnX']) & (df['columnX'] <= y)]

VAR_STR[(VAR_STR <= VAR_STR['VAR_STR']) & (VAR_STR['VAR_STR'] <= VAR_STR)]


remove parentheses only around single words in a string `s` using regex


add variable `var` to key 'f' of first element in JSON data `data`


merge pandas dataframe `x` with columns 'a' and 'b' and dataframe `y` with column 'y'

pd.merge(VAR_STR, VAR_STR, on='k')[['VAR_STR', 'VAR_STR', 'VAR_STR']]


concatenate key/value pairs in dictionary `a` with string ', ' into a single string

""", """.join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])

""", """.join([(str(k) + ' ' + str(v)) for k, v in list(VAR_STR.items())])


match regex pattern 'a*?bc*?' on string 'aabcc' with DOTALL enabled


for (dirname, dirnames, filenames) in os.walk('.'):
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))
    for filename in filenames:
        pass

for dirname, dirnames, filenames in os.walk('VAR_STR'):
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))
    for filename in filenames:
        pass


split a `utf-8` encoded string `stru` into a list of characters


convert a string `s` to its base-10 representation


sort a zipped list `zipped` using lambda function


find all the rows in Dataframe 'df2' that are also present in Dataframe 'df1', for the columns 'A', 'B', 'C' and 'D'.

pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner')

pd.merge(VAR_STR, VAR_STR, on=['VAR_STR', 'VAR_STR', 'VAR_STR', 'VAR_STR'], how='inner')


check if all of the following items in list `['a', 'b']` are in a list `['a', 'b', 'c']`


Check if all the items in a list `['a', 'b']` exists in another list `l`


split string `string` on whitespaces using a generator

return (x.group(0) for x in re.finditer("[A-Za-z']+", string))

return (x.group(0) for x in re.finditer("[A-Za-z']+", VAR_STR))


generate a list containing values associated with the key 'value' of each dictionary inside list `list_of_dicts`


python getting a list of value from list of dict


BeautifulSoup find all 'tr' elements in HTML string `soup` at the five stride starting from the fourth element


get a utf-8 string literal representation of byte string `x`


extract elements at indices (1, 2, 5) from a list `a`


sort list `a` using the first dimension of the element as the key to list `b`


How to sort a list according to another list?


Convert a Unicode string `title` to a 'ascii' string


Convert a Unicode string `a` to a 'ascii' string


delete all occureces of `8` in each string `s` in list `lst`

print([s.replace('8', '') for s in lst])

print([VAR_STR.replace('VAR_STR', '') for VAR_STR in VAR_STR])


replace values of dataframe `df` with True if numeric

df.applymap(lambda x: isinstance(x, (int, float)))

VAR_STR.applymap(lambda x: isinstance(x, (int, float)))


convert values in dictionary `d` into integers


generate the combinations of 3 from a set `{1, 2, 3, 4}`

print(list(itertools.combinations({1, 2, 3, 4}, 3)))


double each character in string `text.read()`


split a string `a , b; cdf`  using both commas and semicolons as delimeters


Split a string `string` by multiple separators `,` and `;`

[t.strip() for s in string.split(',') for t in s.split(';')]

[t.strip() for s in VAR_STR.split('VAR_STR') for t in s.split('VAR_STR')]


sort list `trial_list` based on values of dictionary `trail_dict`

sorted(trial_list, key=lambda x: trial_dict[x])

sorted(VAR_STR, key=lambda x: trial_dict[x])


merge a list of integers `[1, 2, 3, 4, 5]` into a single integer

from functools import reduce
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])

from functools import reduce
reduce(lambda x, y: 10 * x + y, [VAR_STR])


Get all object attributes of object `obj`


create a list containing the multiplication of each elements at the same index of list `lista` and list `listb`

[(a * b) for a, b in zip(VAR_STR, VAR_STR)]


append a path `/path/to/main_folder` in system path


check if any of the items in  `search` appear in `string`


select the first row grouped per level 0 of dataframe `df`


Escape character '}' in string '{0}:<15}}{1}:<15}}{2}:<8}}' while using function `format` with arguments `('1', '2', '3')`


Join data of dataframe `df1` with data in dataframe `df2` based on similar values of column 'user_id' in both dataframes

s1 = pd.merge(df1, df2, how='inner', on=['user_id'])

s1 = pd.merge(VAR_STR, VAR_STR, how='inner', on=['VAR_STR'])


parse string '2015/01/01 12:12am' to DateTime object using format '%Y/%m/%d %I:%M%p'


group dataframe `data` entries by year value of the date in column 'date'


change the size of the sci notation to '30' above the y axis in matplotlib `plt`


get all column name of dataframe `df` except for column 'T1_V6'


removing key values pairs with key 'mykey1' from a list of dictionaries `mylist`

[{k: v for k, v in d.items() if k != 'mykey1'} for d in mylist]

[{k: v for k, v in d.items() if k != 'VAR_STR'} for d in VAR_STR]


Removing key values pairs from a list of dictionaries

[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]


strip the string `.txt` from anywhere in the string `Boat.txt.txt`


split string "0,1,2" based on delimiter ','


convert the string '0,1,2' to a list of integers


execute raw sql queue '<sql here>' in database `db` in sqlalchemy-flask app

result = db.engine.execute('<sql here>')


What is the most pythonic way to exclude elements of a list that start with a specific character?

[x for x in my_list if not x.startswith('#')]


VAR_STR = VAR_STR.replace('VAR_STR', 'VAR_STR')


get a list of last trailing words from another list  of strings`Original_List`

new_list = [x.split()[-1] for x in Original_List]

new_list = [x.split()[-1] for x in VAR_STR]


set the value in column 'B' to NaN if the corresponding value in column 'A' is equal to 0 in pandas dataframe `df`

VAR_STR.ix[VAR_STR.VAR_STR == 0, 'VAR_STR'] = np.nan


reset index to default in dataframe `df`


create a list containing digits of number 123 as its elements


convert generator object to a dictionary


move dictionaries in list `lst` to the end of the list if value of key 'language' in each dictionary is not equal to 'en'

sorted(lst, key=lambda x: x['language'] != 'en')

sorted(VAR_STR, key=lambda x: x['VAR_STR'] != 'VAR_STR')


writing string 'text to write\n' to file `f`


Write a string `My String` to a file `file` including new line character


[m[0] for m in re.compile('VAR_STR').findall('VAR_STR')]


use regular expression '((\\d)(?:[()]*\\2*[()]*)*)' to split string `s`

[i[0] for i in re.findall('VAR_STR', VAR_STR)]


add character '@' after word 'get' in string `text`

VAR_STR = re.sub('(\\bget\\b)', '\\1@', VAR_STR)


serialize dictionary `d` as a JSON formatted string with each key formatted to pattern '%d,%d'

simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))

simplejson.dumps(dict([('VAR_STR' % k, v) for k, v in list(VAR_STR.items())]))


decode escape sequences in string `myString`


remove colon character surrounded by vowels letters in string `word`


group dataframe `df` based on minute interval


Execute a post request to url `http://httpbin.org/post` with json data `{'test': 'cheers'}`


delete all digits in string `s` that are not directly attached to a word character


Delete self-contained digits from string `s`


get the maximum 2 values per row in array `A`


append line "appended text" to file "test.txt"

with open('test.txt', 'a') as myfile:
    myfile.write('appended text')

with open('VAR_STR', 'a') as myfile:
    myfile.write('VAR_STR')


append line "cool beans..." to file "foo"

with open('foo', 'a') as f:
    f.write('cool beans...')

with open('VAR_STR', 'a') as f:
    f.write('VAR_STR')


with open('VAR_STR', 'ab') as f:
    pass


get the name of function `func` as a string


do a boolean check if a string `lestring` contains any of the items in list `lelist`


combine two columns `foo` and `bar` in a pandas data frame


sort a list of dictionaries `a` by dictionary values in descending order

sorted(a, key=lambda i: list(i.values())[0], reverse=True)

sorted(VAR_STR, key=lambda i: list(i.values())[0], reverse=True)


sorting a list of dictionary `a` by values in descending order


split string `s` by '@' and get the first element


Add a tuple with value `another_choice` to a tuple `my_choices`

final_choices = ((another_choice,) + my_choices)


pair each element in list `it` 3 times into a tuple


Sorting while preserving order in python

sorted(enumerate(a), key=lambda x: x[1])


get list of sums of neighboring integers in string `example`

[sum(map(int, s)) for s in example.split()]

[sum(map(int, s)) for s in VAR_STR.split()]


split column 'AB' in dataframe `df` into two columns by first whitespace ' '

VAR_STR['VAR_STR'].str.split(' ', 1, expand=True)


pandas dataframe, how do i split a column 'AB' into two 'A' and 'B' on delimiter ' '

df['VAR_STR'], df['VAR_STR'] = df['VAR_STR'].str.split(' ', 1).str


get multiple parameters with same name from a url in pylons


match contents of an element to 'Example' in xpath (lxml)


find rows of 2d array in 3d numpy array 'arr' if the row has value '[[0, 3], [3, 0]]'

np.argwhere(np.all(VAR_STR == [VAR_STR], axis=(1, 2)))


How to convert a date string '2013-1-25' in format '%Y-%m-%d' to different format '%m/%d/%y'


convert a date string '2013-1-25' in format '%Y-%m-%d' to different format '%-m/%d/%y'


find the count of a word 'Hello' in a string `input_string`


count the number of trailing question marks in string `my_text`


extract dictionary `d` from list `a` where the value associated with the key 'name' of dictionary `d` is equal to 'pluto'

[VAR_STR for VAR_STR in VAR_STR if VAR_STR['VAR_STR'] == 'VAR_STR']


extract dictionary from list of dictionaries based on a key's value.


get second array column length of array `a`


convert the dataframe column 'col' from string types to datetime types


remove all non -word, -whitespace, or -apostrophe characters from string `doesn't this mean it -technically- works?`

re.sub("[^\\w' ]", '', "doesn't this mean it -technically- works?")


find the index of the element with the maximum value from a list 'a'.

max(enumerate(a), key=lambda x: x[1])[0]

max(enumerate(VAR_STR), key=lambda x: x[1])[0]


Check if string 'a b' only contains letters and spaces


pad 'dog' up to a length of 5 characters with 'x'


find all substrings in string `mystring` composed only of letters `a` and `b` where each `a` is directly preceded and succeeded by `b`


check if a checkbox is checked in selenium python webdriver


determine if checkbox with id '<check_box_id>' is checked in selenium python webdriver


Find all keys from a dictionary `d` whose values are `desired_value`

[k for k, v in d.items() if v == desired_value]

[k for k, v in VAR_STR.items() if v == VAR_STR]


sort a multidimensional array `a` by column with index 1


sum the length of all strings in a list `strings`


Convert a list of lists `lol` to a dictionary with key as second value of a list and value as list itself


get data of column 'A' and column 'B' in dataframe `df` where column 'A' is equal to 'foo'


display a pdf  file that has been downloaded as `my_pdf.pdf`


sort 2d array `matrix` by row with index 1


get the maximum string length in nested list `i`


print a string after a specific substring ', ' in string `my_string `


extract attribute `my_attr` from each object in list `my_list`


set the value of cell `['x']['C']` equal to 10 in dataframe `df`


how to get month name of datetime `today`


get month name from a datetime object `today`


execute shell command 'grep -r PASSED *.log | sort -u | wc -l' with a | pipe in it

subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)


Converting string lists `s` to float list

floats = [float(x) for x in VAR_STR.split()]


Execute Shell Script from python with variable


count the number of integers in list `a`

sum(isinstance(x, int) for x in VAR_STR)


save json output from a url ‘http://search.twitter.com/search.json?q=hi’ to file ‘hi.json’ in Python 2

urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi',
    'hi.json')


remove uppercased characters in string `s`


Get a list of lists with summing the values of the second element from each list of lists `data`

[[sum([x[1] for x in i])] for i in data]

[[sum([x[1] for x in i])] for i in VAR_STR]


summing the second item in a list of lists of lists


apply functions `mean` and `std` to each column in dataframe `df`

df.groupby(lambda idx: 0).agg(['mean', 'std'])

VAR_STR.groupby(lambda idx: 0).agg(['VAR_STR', 'VAR_STR'])


count the number of non-nan elements in a numpy ndarray matrix `data`


How can I resize the root window in Tkinter?


add header 'WWWAuthenticate' in a flask app with value 'Basic realm="test"'

response.headers['WWW-Authenticate'] = 'Basic realm="test"'


return the column for value 38.15 in dataframe `df`

VAR_STR.ix[:, (VAR_STR.loc[0] == 38.15)].columns


sort two lists `list1` and `list2` together using lambda function

[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]

[list(x) for x in zip(*sorted(zip(VAR_STR, VAR_STR), key=lambda pair: pair[0]))]


drop duplicate indexes in a pandas data frame `df`


grab one random item from a database `model` in django/postgresql


select a first form with no name in mechanize


convert a list of objects `list_name` to json string `json_string`

json_string = json.dumps([ob.__dict__ for ob in list_name])

VAR_STR = json.dumps([ob.__dict__ for ob in VAR_STR])


Get a list comparing two lists of tuples `l1` and `l2` if any first value in `l1` matches with first value in `l2`

[x[0] for x in l1 if any(x[0] == y[0] for y in l2)]

[x[0] for x in VAR_STR if any(x[0] == y[0] for y in VAR_STR)]


remove all words which contains number from a string `words` using regex


match a sharp, followed by letters (including accent characters) in string `str1` using a regex

hashtags = re.findall('#(\\w+)', str1, re.UNICODE)

hashtags = re.findall('#(\\w+)', VAR_STR, re.UNICODE)


Concat a list of strings `lst` using string formatting


send cookies `cookie` in a post request to url 'http://wikipedia.org' with the python requests library

r = requests.post('http://wikipedia.org', cookies=cookie)

r = requests.post('VAR_STR', cookies=VAR_STR)


list comprehension that produces integers between 11 and 19

[i for i in range(100) if i > 10 if i < 20]


unquote a urlencoded unicode string '%0a'


decode url `url` from UTF-16 code to UTF-8 code


time.strftime('%l:%M%p %z on %b %d, %Y')


replace nans by preceding values in pandas dataframe `df`


sort list `list_` based on first element of each tuple and by the length of the second element of each tuple

list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])

VAR_STR.sort(key=lambda x: [x[0], len(x[1]), x[1]])


sort a multidimensional list `a` by second and third column


Get all indexes of a list `a` where each value is greater than `2`

[i for i in range(len(VAR_STR)) if VAR_STR[i] > 2]


replace special characters in url 'http://spam.com/go/' using the '%xx' escape


execute a command in the command prompt to list directory contents of the c drive `c:\\'


Compose keys from dictionary `d1` with respective values in dictionary `d2`

result = {k: d2.get(v) for k, v in list(d1.items())}

result = {k: VAR_STR.get(v) for k, v in list(VAR_STR.items())}


find all the elements that consists value '1' in a list of tuples 'a'


find all elements in a list of tuples `a` where the first element of each tuple equals 1

[item for item in VAR_STR if item[0] == 1]


execute os command ''TASKKILL /F /IM firefox.exe''

os.system('TASKKILL /F /IM firefox.exe')


copy file "/dir/file.ext" to "/new/dir/newname.ext"


Get a string with string formatting from dictionary `d`

""", """.join(['{}_{}'.format(k, v) for k, v in VAR_STR.items()])


get the ASCII value of a character 'a' as an int


get the ASCII value of a character u'あ' as an int


get the ASCII value of a character as an int


What's the best way to search for a Python dictionary value in a list of dictionaries?

any(d['site'] == 'Superuser' for d in data)


return dataframe `df` with last row dropped


separate numbers from characters in string "30m1000n20m"


separate numbers and characters in string '20M10000N80M'


manually throw/raise a `ValueError` exception with the message 'A very specific bad thing happened'

raise ValueError('A very specific bad thing happened')


Manually throw an exception "I know python!"


throw a ValueError with message 'represents a hidden bug, do not catch this'

raise ValueError('represents a hidden bug, do not catch this')


throw an Exception with message 'This is the exception you expect to handle'

raise Exception('This is the exception you expect to handle')


throw a value error with message 'A very specific bad thing happened', 'foo', 'bar', 'baz'


throw a runtime error with message 'specific message'


throw an assertion error with message "Unexpected value of 'distance'!", distance

raise AssertionError("Unexpected value of 'distance'!", distance)


get unique values from the list `['a', 'b', 'c', 'd']`


get list of duplicated elements in range of 3


remove elements in list `b` from list `a`

[x for x in VAR_STR if x not in VAR_STR]


create a list `matrix` containing 5 lists, each of 5 items  all set to 0


interleave the elements of two lists `a` and `b`

[j for i in zip(VAR_STR, VAR_STR) for j in i]


merge two lists `a` and `b` into a single list


SQLite get a list of column names from cursor object `cursor`

names = list(map(lambda x: x[0], cursor.description))

names = list(map(lambda x: x[0], VAR_STR.description))


select the last business day of the month for each month in 2014 in pandas


rename `last` row index label in dataframe `df` to `a`

VAR_STR = VAR_STR.rename(index={VAR_STR: 'VAR_STR'})


Finding the largest delta between two integers in a list in python

max(abs(x - y) for x, y in zip(values[1:], values[:-1]))


Unzip a list of tuples `l` into a list of lists


reduce the first element of list of strings `data` to a string, separated by '.'

print('.'.join([item[0] for item in data]))

print('VAR_STR'.join([item[0] for item in VAR_STR]))


get the first element of each tuple from a list of tuples `G`


create list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integers

changed_list = [(int(f) if f.isdigit() else f) for f in original_list]

VAR_STR = [(int(f) if f.isdigit() else f) for f in VAR_STR]


regular expression syntax for not to match anything


create a regular expression object with a pattern that will match nothing


convert a list of strings `lst` to list of integers

[map(int, sublist) for sublist in VAR_STR]


convert strings in list-of-lists `lst` to ints

[[int(x) for x in sublist] for sublist in lst]

[[int(x) for x in sublist] for sublist in VAR_STR]


create a list with the characters of a string `5+6`


How to download a file via FTP with Python ftplib

ftp.retrbinary('RETR %s' % filename, file.write)


print the number of occurences of not `none` in a list `lst` in Python 2

print(len([x for x in lst if x is not None]))

print(len([x for x in VAR_STR if x is not None]))


sort a python dictionary `a_dict` by element `1` of the value

sorted(list(a_dict.items()), key=lambda item: item[1][1])

sorted(list(VAR_STR.items()), key=lambda item: item[1][1])


delete an item `thing` in a list `some_list` if it exists

cleaned_list = [x for x in some_list if x is not thing]

cleaned_list = [x for x in VAR_STR if x is not VAR_STR]


get the number of all keys in the nested dictionary `dict_list`

len(dict_test) + sum(len(v) for v in dict_test.values())


find the sums of length 7 subsets of a list `daily`

weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]

weekly = [sum(visitors[x:x + 7]) for x in range(0, len(VAR_STR), 7)]


Get a list of all keys from dictionary `dictA` where the number of occurrences of value `duck` in that key is more than `1`

[k for k, v in dictA.items() if v.count('duck') > 1]

[k for k, v in VAR_STR.items() if v.count('VAR_STR') > 1]


generate a list of consecutive integers from 0 to 8


getting every possible combination of two elements in a list

list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))


split string 'x+13.5*10x-4e1' into tokens

print([i for i in re.split('([\\d.]+|\\W+)', 'VAR_STR') if i])


unpack elements of list `i` as arguments into function `foo`


remove all square brackets from string 'abcd[e]yth[ac]ytwec'


set dataframe `df` index using column 'month'


get a list of the row names from index of a pandas data frame


get the row names from index in a pandas data frame


filtering out strings that contain 'ab' from a list of strings `lst`


From a list of strings `my_list`, remove the values that contains numbers.

[x for x in my_list if not any(c.isdigit() for c in x)]

[x for x in VAR_STR if not any(c.isdigit() for c in x)]


split string `text` into chunks of 16 characters each


remove line breaks from string `textblock` using regex


convert scientific notation of variable `a` to decimal


create a list containing the indices of elements greater than 4 in list `a`

[i for i, v in enumerate(VAR_STR) if v > 4]


split 1d array `a` into 2d array at the last element


convert dataframe `df` to list of dictionaries including the index values


Create list of dictionaries from pandas dataframe `df`


y = map(operator.itemgetter(0), VAR_STR)


get a list `y` of the first element of every tuple in list `x`


Group a pandas data frame by monthly frequenct `M` using groupby


a = [(sum(x) / len(x)) for x in zip(*a)]

VAR_STR = [(sum(x) / len(x)) for x in zip(*VAR_STR)]


Get the age of directory (or file) `/tmp` in seconds.


Convert string to boolean from defined set of strings

s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']


Format string `hello {name}, how are you {name}, welcome {name}` to be interspersed by `name` three times, specifying the value as `john` only once

"""hello {name}, how are you {name}, welcome {name}""".format(name='john')


divide the members of a list `conversions` by the corresponding members of another list `trials`

[(c / t) for c, t in zip(conversions, trials)]

[(c / t) for c, t in zip(VAR_STR, VAR_STR)]


searche in HTML string for elements that have text 'Python'


BeautifulSoup find string 'Python Jobs' in HTML body `body`


Initialize a list `a` with `10000` items and each item's value `0`


Sort lists in the list `unsorted_list` by the element at index 3 of each list


Replace NaN values in  column 'value' with the mean of data in column 'group' of dataframe `df`


add a path `/path/to/2014_07_13_test` to system path


Split string with comma (,) and remove whitespace from a string 'my_string'

[item.strip() for item in my_string.split(',')]

[item.strip() for item in VAR_STR.split(',')]


Match regex pattern '((?:A|B|C)D)' on string 'BDE'


create list `done` containing permutations of each element in list `[a, b, c, d]` with variable `x` as tuples

VAR_STR = [(el, VAR_STR) for el in [VAR_STR]]


How do I find an element that contains specific text in Selenium Webdriver (Python)?


Selecting Element "//li/label/input" followed by text "polishpottery" with Selenium WebDriver `driver`


Resample dataframe `frame` to resolution of 1 hour `1H` for timeseries index, summing values in the column `radiation` averaging those in column `tamb`

frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})

VAR_STR.resample('VAR_STR').agg({'VAR_STR': np.sum, 'VAR_STR': np.mean})


sum each element `x` in list `first` with element `y` at the same index in list `second`.

[(x + y) for x, y in zip(first, second)]

[(VAR_STR + VAR_STR) for VAR_STR, VAR_STR in zip(VAR_STR, VAR_STR)]


get the context of a search by keyword 'My keywords' in beautifulsoup `soup`

k = soup.find(text=re.compile('My keywords')).parent.text


sort list `xs` based on the length of its elements


sort list `xs` in ascending order of length of elements

xs.sort(lambda x, y: cmp(len(x), len(y)))

VAR_STR.sort(lambda x, y: cmp(len(x), len(y)))


sort list of strings `xs` by the length of string


Make a dictionary from list `f` which is in the format of four sets of  "val, key, val"

{VAR_STR[i + 1]: [VAR_STR[i], VAR_STR[i + 2]] for i in range(0, len(VAR_STR), 3)}


check if string `string` starts with a number


Check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')

VAR_STR.startswith(('VAR_STR', 'VAR_STR', 'VAR_STR', 'VAR_STR', 'VAR_STR', 'VAR_STR',
    'VAR_STR', 'VAR_STR', 'VAR_STR', 'VAR_STR'))


create a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehension

[y['baz'] for x in foos for y in x['bar']]

[y['VAR_STR'] for x in VAR_STR for y in x['bar']]


Make a auto scrolled window to the end of the list in gtk


Creating a list of dictionaries in python


print('Value is "' + str(VAR_STR) + '"')


Print a string `value` with string formatting


get index of the biggest 2 values of a list `a`

sorted(list(range(len(a))), key=lambda i: a[i])[-2:]

sorted(list(range(len(VAR_STR))), key=lambda i: VAR_STR[i])[-2:]


get indexes of the largest `2` values from a list `a` using itemgetter


get the indexes of the largest `2` values from a list of integers `a`

sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]

sorted(list(range(len(VAR_STR))), key=lambda i: VAR_STR[i], reverse=True)[:2]


cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))

cursor.execute('INSERT INTO index(url) VALUES(%s)', (VAR_STR,))


self.myList.extend([0] * (4 - len(self.myList)))

self.VAR_STR.extend([0] * (4 - len(self.VAR_STR)))


immediately see output of print statement that doesn't end in a newline


check if all values of a dictionary `your_dict` are zero `0`

all(value == 0 for value in list(your_dict.values()))

all(value == 0 for value in list(VAR_STR.values()))


count number of occurrences of a substring 'ab' in a string "abcdabcva"


get the union set from list of lists `results_list`


get the union of values in list of lists `result_list`


make a flat list from list of lists `sublist`

[item for sublist in l for item in sublist]

[item for VAR_STR in l for item in VAR_STR]


make a flat list from list of lists `list2d`


join two dataframes based on values in selected columns

pd.merge(a, b, on=['A', 'B'], how='outer')


get all the values in column `b` from pandas data frame `df`


convert Date object `dateobject` into a DateTime object


How to exclude a character from a regex group?


index a list `L` with another list `Idx`


How to plot two columns of a pandas data frame using points?


remove all non-numeric characters from string `sdkjh987978asd098as0980a98sd `


finding the index of an item 'foo' given a list `['foo', 'bar', 'baz']` containing it

[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']

[i for i, j in enumerate(['VAR_STR', 'bar', 'baz']) if j == 'VAR_STR']


subtract elements of list `List1` from elements of list `List2`

[(x1 - x2) for x1, x2 in zip(List1, List2)]

[(x1 - x2) for x1, x2 in zip(VAR_STR, VAR_STR)]


extract date from a string 'monkey 2010-07-32 love banana'

dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)


extract date from a string 'monkey 20/01/1980 love banana'

dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)


extract date from a string `monkey 10/01/1980 love banana`

dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)


remove a key 'key' from a dictionary `my_dict`


How to get the concrete class name as a string?


sort list `a` in ascending order based on its elements' float values

VAR_STR = sorted(VAR_STR, key=lambda x: float(x))


Sort list `alist` in ascending order based on each of its elements' attribute `foo`


open file '5_1.txt' in directory `direct`

x_file = open(os.path.join(direct, '5_1.txt'), 'r')

x_file = open(os.path.join(VAR_STR, 'VAR_STR'), 'r')


save numpy array `x` into text file 'test.txt'