text
stringlengths
4
1.08k
Delete letters from string,""""""""""""".join(filter(str.isdigit, '12454v'))"
applying regex to a pandas dataframe,df['Season'].str.split('-').str[0].astype(int)
Sort tuples based on second parameter,my_list.sort(key=lambda x: x[1])
Find all occurrences of a substring in Python,"[m.start() for m in re.finditer('(?=tt)', 'ttt')]"
Find all occurrences of a substring in Python,"[m.start() for m in re.finditer('test', 'test test test test')]"
re.split with spaces in python,"re.findall('\\s+|\\S+', s)"
Working with set_index in Pandas DataFrame,"rdata.set_index(['race_date', 'track_code', 'race_number'])"
recursively go through all subdirectories and read files,"for (root, subFolders, files) in os.walk(rootdir):
pass"
sorting a list of dictionary values by date in python,"list.sort(key=lambda item: item['date'], reverse=True)"
How to truncate a string using str.format in Python?,"""""""{:.5}"""""".format('aaabbbccc')"
How do I convert a string of hexadecimal values to a list of integers?,"struct.unpack('11B', s)"
Finding the index of an item given a list containing it in Python,"[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']"
How to generate all permutations of a list in Python,"print(list(itertools.product([1, 2, 3], [4, 5, 6])))"
How to generate all permutations of a list in Python,"itertools.permutations([1, 2, 3])"
Remove punctuation from Unicode formatted strings,"return re.sub('\\p{P}+', '', text)"
manually throw/raise an exception,raise ValueError('A very specific bad thing happened')
Manually raising (throwing) an exception,raise Exception('I know Python!')
Manually raising (throwing) an exception,raise Exception('I know python!')
Manually raising (throwing) an exception,"raise ValueError('represents a hidden bug, do not catch this')"
Manually raising (throwing) an exception,raise Exception('This is the exception you expect to handle')
Manually raising (throwing) an exception,raise ValueError('A very specific bad thing happened')
Manually raising (throwing) an exception,raise RuntimeError('specific message')
Manually raising (throwing) an exception,"raise AssertionError(""Unexpected value of 'distance'!"", distance)"
Clear text from textarea with selenium,driver.find_element_by_id('foo').clear()
Clear text from textarea with selenium,driver.find_element_by_id('foo').clear()
Convert an IP string to a number and vice versa,"socket.inet_ntoa(struct.pack('!L', 2130706433))"
How to rearrange Pandas column sequence?,"df = df[['x', 'y', 'a', 'b']]"
How to call Base Class's __init__ method from the child class?,"super(ChildClass, self).__init__(*args, **kwargs)"
Sum of all values in a Python dict,sum(d.values())
Sum of all values in a Python dict,sum(d.values())
Convert Python dictionary to JSON array,"json.dumps(your_data, ensure_ascii=False)"
numpy array assignment using slicing,"values = np.array([i for i in range(100)], dtype=np.float64)"
Sort a list of dictionary provided an order,"sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))"
how to change the case of first letter of a string?,return s[0].upper() + s[1:]
"how to change [1,2,3,4] to '1234' using python",""""""""""""".join([1, 2, 3, 4])"
Delete every non utf-8 symbols froms string,"line = line.decode('utf-8', 'ignore').encode('utf-8')"
How to execute a command in the terminal from a Python script?,os.system(command)
Python MySQL Parameterized Queries,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))"
Convert a string to datetime object in python,"dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()"
Concatenate elements of a list 'x' of multiple integers to a single integer,"sum(d * 10 ** i for i, d in enumerate(x[::-1]))"
convert a list of integers into a single integer,"r = int(''.join(map(str, x)))"
convert a DateTime string back to a DateTime object of format '%Y-%m-%d %H:%M:%S.%f',"datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')"
get the average of a list values for each key in dictionary `d`),"[(i, sum(j) / len(j)) for i, j in list(d.items())]"
"zip two lists `[1, 2]` and `[3, 4]` into a list of two tuples containing elements at the same index in each list","zip([1, 2], [3, 4])"
prepend string 'hello' to all items in list 'a',['hello{0}'.format(i) for i in a]
regex for repeating words in a string `s`,"re.sub('(?<!\\S)((\\S+)(?:\\s+\\2))(?:\\s+\\2)+(?!\\S)', '\\1', s)"
normalize a pandas dataframe `df` by row,"df.div(df.sum(axis=1), axis=0)"
swap values in a tuple/list inside a list `mylist`,"map(lambda t: (t[1], t[0]), mylist)"
Swap values in a tuple/list in list `mylist`,"[(t[1], t[0]) for t in mylist]"
Find next sibling element in Python Selenium?,"driver.find_element_by_xpath(""//p[@id, 'one']/following-sibling::p"")"
"find all occurrences of the pattern '\\[[^\\]]*\\]|\\([^\\)]*\\)|""[^""]*""|\\S+' within `strs`","re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|""[^""]*""|\\S+', strs)"
"generate the combinations of 3 from a set `{1, 2, 3, 4}`","print(list(itertools.combinations({1, 2, 3, 4}, 3)))"
"add multiple columns `hour`, `weekday`, `weeknum` to pandas data frame `df` from lambda function `lambdafunc`","df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)"
BeautifulSoup search string 'Elsie' inside tag 'a',"soup.find_all('a', string='Elsie')"
"Convert a datetime object `my_datetime` into readable format `%B %d, %Y`","my_datetime.strftime('%B %d, %Y')"
parse string `s` to int when string contains a number,int(''.join(c for c in s if c.isdigit()))
add dictionary `{'class': {'section': 5}}` to key 'Test' of dictionary `dic`,dic['Test'].update({'class': {'section': 5}})
transforming the string `s` into dictionary,"dict(map(int, x.split(':')) for x in s.split(','))"
How to select element with Selenium Python xpath,"driver.find_element_by_xpath(""//div[@id='a']//a[@class='click']"")"
"find rows matching `(0,1)` in a 2 dimensional numpy array `vals`","np.where((vals == (0, 1)).all(axis=1))"
How to delete a record in Django models?,SomeModel.objects.filter(id=id).delete()
"build a dictionary containing the conversion of each list in list `[['two', 2], ['one', 1]]` to a key/value pair as its items","dict([['two', 2], ['one', 1]])"
convert list `l` to dictionary having each two adjacent elements as key/value pair,"dict(zip(l[::2], l[1::2]))"
assign float 9.8 to variable `GRAVITY`,GRAVITY = 9.8
"separate numbers from characters in string ""30m1000n20m""","re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')"
separate numbers and characters in string '20M10000N80M',"re.findall('([0-9]+|[A-Z])', '20M10000N80M')"
separate numbers and characters in string '20M10000N80M',"re.findall('([0-9]+)([A-Z])', '20M10000N80M')"
"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!')"
Convert string '03:55' into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()"
request url 'https://www.reporo.com/' without verifying SSL certificates,"requests.get('https://www.reporo.com/', verify=False)"
Extract values not equal to 0 from numpy array `a`,a[a != 0]
map two lists `keys` and `values` into a dictionary,"new_dict = {k: v for k, v in zip(keys, values)}"
map two lists `keys` and `values` into a dictionary,"dict((k, v) for k, v in zip(keys, values))"
map two lists `keys` and `values` into a dictionary,"dict([(k, v) for k, v in zip(keys, values)])"
find the string matches within parenthesis from a string `s` using regex,"m = re.search('\\[(\\w+)\\]', s)"
Enable the SO_REUSEADDR socket option in socket object `s` to fix the error `only one usage of each socket address is normally permitted`,"s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)"
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)]"
converting hex string `s` to its integer representations,[ord(c) for c in s.decode('hex')]
sort list `student_tuples` by second element of each tuple in ascending and third element of each tuple in descending,"print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))"
get list of duplicated elements in range of 3,"[y for x in range(3) for y in [x, x]]"
read the contents of the file 'file.txt' into `txt`,txt = open('file.txt').read()
divide each element in list `myList` by integer `myInt`,myList[:] = [(x / myInt) for x in myList]
python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})"
replace white spaces in dataframe `df` with '_',"df.replace(' ', '_', regex=True)"
convert date `my_date` to datetime,"datetime.datetime.combine(my_date, datetime.time.min)"
convert tuple `tst` to string `tst2`,tst2 = str(tst)
get modified time of file `file`,time.ctime(os.path.getmtime(file))
get creation time of file `file`,time.ctime(os.path.getctime(file))
get modification time of file `filename`,t = os.path.getmtime(filename)
get modification time of file `path`,os.path.getmtime(path)
get modified time of file `file`,print(('last modified: %s' % time.ctime(os.path.getmtime(file))))
get the creation time of file `file`,print(('created: %s' % time.ctime(os.path.getctime(file))))
get the creation time of file `path_to_file`,return os.path.getctime(path_to_file)
execute os command ''TASKKILL /F /IM firefox.exe'',os.system('TASKKILL /F /IM firefox.exe')
split string `string` on whitespaces using a generator,"return (x.group(0) for x in re.finditer(""[A-Za-z']+"", string))"
Unpack each value in list `x` to its placeholder '%' in string '%.2f',""""""", """""".join(['%.2f'] * len(x))"
match regex pattern '(\\d+(\\.\\d+)?)' with string '3434.35353',"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))"
replace parentheses and all data within it with empty string '' in column 'name' of dataframe `df`,"df['name'].str.replace('\\(.*\\)', '')"
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]