text
stringlengths
4
1.08k
How to remove all the punctuation in a string? (Python),"out = ''.join(c for c in asking if c not in ('!', '.', ':'))"
Python: BeautifulSoup - get an attribute value based on the name attribute,"soup.find('meta', {'name': 'City'})['content']"
How to unquote a urlencoded unicode string in python?,urllib.parse.unquote('%0a')
How to unquote a urlencoded unicode string in python?,urllib.parse.unquote(url).decode('utf8')
empty a list,del lst[:]
empty a list,del lst1[:]
empty a list,lst[:] = []
empty a list,alist[:] = []
Pandas reset index on series to remove multiindex,s.reset_index(0).reset_index(drop=True)
How to convert unicode text to normal text,elems[0].getText().encode('utf-8')
Subtracting the current and previous item in a list,"[(y - x) for x, y in zip(L, L[1:])]"
Cleanest way to get a value from a list element,"print(re.search('\\bLOG_ADDR\\s+(\\S+)', line).group(1))"
Importing everything ( * ) dynamically from a module,globals().update(importlib.import_module('some.package').__dict__)
Convert a list of characters into a string,""""""""""""".join(['a', 'b', 'c', 'd'])"
Slicing URL with Python,url.split('&')
sort a dictionary by key,od = collections.OrderedDict(sorted(d.items()))
sort a dictionary by key,"OrderedDict(sorted(list(d.items()), key=(lambda t: t[0])))"
PUT Request to REST API using Python,"response = requests.put(url, data=json.dumps(data), headers=headers)"
Python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s)"
Python Nested List Comprehension with two Lists,[(x + y) for x in l2 for y in l1]
convert string to dict using list comprehension in python,dict([x.split('=') for x in s.split()])
Remove object from a list of objects in python,my_list.pop(2)
How to delete a character from a string using python?,"s = s.replace('M', '')"
How to delete a character from a string using python?,"newstr = oldstr.replace('M', '')"
How can I sum the product of two list items using for loop in python?,"sum(x * y for x, y in zip(a, b))"
How can I sum the product of two list items using for loop in python?,"list(x * y for x, y in list(zip(a, b)))"
How can I sum the product of two list items using for loop in python?,"sum(i * j for i, j in zip(a, b))"
How can I sum the product of two list items using for loop in python?,"sum(x * y for x, y in list(zip(a, b)))"
Can I read and write file in one line with Python?,"f.write(open('xxx.mp4', 'rb').read())"
How to add an integer to each element in a list?,new_list = [(x + 1) for x in my_list]
Return list of items in list greater than some value,[x for x in j if x >= 5]
matplotlib: Set markers for individual points on a line,"plt.plot(list(range(10)), '--bo')"
matplotlib: Set markers for individual points on a line,"plt.plot(list(range(10)), linestyle='--', marker='o', color='b')"
split elements of a list in python,"[i.split('\t', 1)[0] for i in l]"
split elements of a list in python,myList = [i.split('\t')[0] for i in myList]
Summing elements in a list,sum(your_list)
How to attach debugger to a python subproccess?,ForkedPdb().set_trace()
Python: comprehension to compose two dictionaries,"result = {k: d2.get(v) for k, v in list(d1.items())}"
datetime.datetime.now() + 1,"datetime.datetime.now() + datetime.timedelta(days=1, hours=3)"
Convert binary string to list of integers using Python,"[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]"
switching keys and values in a dictionary in python,"dict((v, k) for k, v in my_dict.items())"
Specific sort a list of numbers separated by dots,"print(sorted(L, key=lambda x: int(x.split('.')[2])))"
How to find a value in a list of python dictionaries?,any(d['name'] == 'Test' for d in label)
How can I remove all instances of an element from a list in Python?,"a[:] = [x for x in a if x != [1, 1]]"
How can I remove all instances of an element from a list in Python?,"[x for x in a if x != [1, 1]]"
Convert a list to a dictionary in Python,"b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}"
How to check whether elements appears in the list only once in python?,len(set(a)) == len(a)
Generating an MD5 checksum of a file,"print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())"
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])"
Pythons fastest way of randomising case of a string,""""""""""""".join(x.upper() if random.randint(0, 1) else x for x in s)"
How to force os.system() to use bash instead of shell,"os.system('GREPDB=""echo 123""; /bin/bash -c ""$GREPDB""')"
How to force os.system() to use bash instead of shell,"os.system('/bin/bash -c ""echo hello world""')"
how to access the class variable by string in Python?,"getattr(test, a_string)"
How to display a jpg file in Python?,Image.open('pathToFile').show()
Replace the single quote (') character from a string,"""""""didn't"""""".replace(""'"", '')"
Sorting files in a list,files.sort(key=file_number)
remove all whitespace in a string,"sentence.replace(' ', '')"
remove all whitespace in a string,"pattern = re.compile('\\s+')
sentence = re.sub(pattern, '', sentence)"
remove all whitespace in a string,sentence.strip()
remove all whitespace in a string,"sentence = re.sub('\\s+', '', sentence, flags=re.UNICODE)"
remove all whitespace in a string,sentence = ''.join(sentence.split())
Sum all values of a counter in Python,sum(my_counter.values())
Numpy: find the euclidean distance between two 3-D arrays,np.sqrt(((A - B) ** 2).sum(-1))
Python: define multiple variables of same type?,"levels = [{}, {}, {}]"
Find the sum of subsets of a list in python,"weekly = [sum(visitors[x:x + 7]) for x in range(0, len(daily), 7)]"
Delete an element from a dictionary,del d[key]
Delete an element from a dictionary,{i: a[i] for i in a if (i != 0)}
Delete an element from a dictionary,lol.pop('hello')
Delete an element from a dictionary,del r[key]
Efficient computation of the least-squares algorithm in NumPy,"np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))"
Splitting dictionary/list inside a Pandas Column into Separate Columns,"pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)"
loop through a Python list by twos,"for i in range(0, 10, 2):
pass"
loop through a Python list by twos,"for i in mylist[::2]:
pass"
How to use map to lowercase strings in a dictionary?,[{'content': x['content'].lower()} for x in messages]
convert list into string with spaces in python,""""""" """""".join(my_list)"
Regex. Match words that contain special characters or 'http://',"re.sub('(http://\\S+|\\S*[^\\w\\s]\\S*)', '', a)"
How to check for palindrome using Python logic,str(n) == str(n)[::-1]
How to upload binary file with ftplib in Python?,"ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))"
How to remove all characters before a specific character in Python?,"re.sub('.*I', 'I', stri)"
Python parse comma-separated number into int,"int('1,000,000'.replace(',', ''))"
Combine two Pandas dataframes with the same index,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer')"
Combine two Pandas dataframes with the same index,"pandas.concat([df1, df2], axis=1)"
What's the best way to aggregate the boolean values of a Python dictionary?,all(dict.values())
How to extract first two characters from string using regex,"df.c_contofficeID.str.replace('^12(?=.{4}$)', '')"
reverse a list,L[::(-1)]
reverse a list,reversed(array)
reverse a list,L.reverse()
reverse a list,list(reversed(array))
How to index nested lists in Python?,[tup[0] for tup in A]
Replacing characters in a file,"newcontents = contents.replace('a', 'e').replace('s', '3')"
How to serialize SqlAlchemy result to JSON?,json.dumps([dict(list(row.items())) for row in rs])
Cross-platform addressing of the config file,config_file = os.path.expanduser('~/foo.ini')
How to get multiple parameters with same name from a URL in Pylons?,request.params.getall('c')
how to create similarity matrix in numpy python?,np.corrcoef(x)
Python - Find the greatest number in a set of numbers,"print(max(1, 2, 3))"
Google App Engine - Request class query_string,self.request.get('var_name')
python pandas: apply a function with arguments to a series. Update,"a['x'].apply(lambda x, y: x + y, args=(100,))"