text
stringlengths
4
1.08k
Parsing string containing Unicode character names,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape')
Parsing string containing Unicode character names,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.decode('unicode-escape')
Convert unicode codepoint to UTF8 hex in python,"chr(int('fd9b', 16)).encode('utf-8')"
How can I get Python to use upper case letters to print hex values?,print('0x%X' % value)
How to remove empty string in a list?,cleaned = [x for x in your_list if x]
Python: Want to use a string as a slice specifier,slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])
Beautiful Soup Using Regex to Find Tags?,"soup.find_all(['a', 'div'])"
Get function name as a string in python,print(func.__name__)
How to convert dictionary into string,""""""""""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))"
How to convert dictionary into string,""""""""""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))"
copy a list,new_list = old_list[:]
copy a list,new_list = list(old_list)
copy a list,new_list = copy.copy(old_list)
copy a list,new_list = copy.deepcopy(old_list)
copy a list,[i for i in old_list]
Remove or adapt border of frame of legend using matplotlib,plt.legend(frameon=False)
How to work with surrogate pairs in Python?,"""""""\\ud83d\\ude4f"""""".encode('utf-16', 'surrogatepass').decode('utf-16')"
Calling a function of a module from a string with the function's name in Python,globals()['myfunction']()
Checking if a website is up,urllib.request.urlopen('http://www.stackoverflow.com').getcode()
Checking if a website is up,"r = requests.head(url)
return (r.status_code == 200)"
Checking if a website is up,print(urllib.request.urlopen('http://www.stackoverflow.com').getcode())
Selenium open pop up window [Python],"driver.find_element_by_css_selector(""a[href^='javascript']"").click()"
"How to store data frame using PANDAS, Python",df.to_pickle(file_name)
Pandas: Mean of columns with the same names,"df.groupby(by=df.columns, axis=1).mean()"
How to perform double sort inside an array?,"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)"
How to get alpha value of a PNG image with PIL?,alpha = img.split()[-1]
How to get the length of words in a sentence?,[len(x) for x in s.split()]
Find a specific tag with BeautifulSoup,"soup.findAll('div', style='width=300px;')"
Using a Python dict for a SQL INSERT statement,"cursor.execute(sql, list(myDict.values()))"
Preserving Column Order - Python Pandas and Column Concat,"df.to_csv('Result.csv', index=False, sep=' ')"
Python: Extract variables out of namespace,globals().update(vars(args))
Regular expression to return all characters between two special characters,"re.findall('\\[(.*?)\\]', mystring)"
"Python, print all floats to 2 decimal places in output","print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))"
The best way to filter a dictionary in Python,"d = dict((k, v) for k, v in d.items() if v > 0)"
The best way to filter a dictionary in Python,"d = {k: v for k, v in list(d.items()) if v > 0}"
In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?,pd.to_datetime(pd.Series(date_stngs))
Print the complete string of a pandas dataframe,"df.iloc[2, 0]"
How to change the font size on a matplotlib plot,matplotlib.rcParams.update({'font.size': 22})
Convert Python dict into a dataframe,"pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])"
Pandas: Elementwise multiplication of two dataframes,"pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)"
How to extract a floating number from a string,"re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')"
How to extract a floating number from a string,"re.findall('[-+]?\\d*\\.\\d+|\\d+', 'Current Level: -13.2 db or 14.2 or 3')"
Convert List to a list of tuples python,"zip(it, it, it)"
How to lowercase a python dataframe string column if it has missing values?,df['x'].str.lower()
python append to array in json object,"jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})"
Most Pythonic way to concatenate strings,""""""""""""".join(lst)"
Python: Sum values in a dictionary based on condition,sum(v for v in list(d.values()) if v > 0)
Flask application traceback doesn't show up in server log,app.run(debug=True)
How to drop a list of rows from Pandas dataframe?,"df.drop(df.index[[1, 3]], inplace=True)"
pandas DataFrame: replace nan values with average of columns,"df.apply(lambda x: x.fillna(x.mean()), axis=0)"
How to extract from a list of objects a list of specific attribute?,[o.my_attr for o in my_list]
python get time stamp on file in mm/dd/yyyy format,"time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))"
Python: Check if one dictionary is a subset of another larger dictionary,all(item in list(superset.items()) for item in list(subset.items()))
Python: for loop in index assignment,[str(wi) for wi in wordids]
Indexing a pandas dataframe by integer,df2 = df.reset_index()
Convert datetime object to a String of date only in Python,dt.strftime('%m/%d/%Y')
Python Add Comma Into Number String,"print('Total cost is: ${:,.2f}'.format(TotalAmount))"
Sum of Every Two Columns in Pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')"
creating list of random numbers in python,randomList = [random.random() for _ in range(10)]
beautifulsoup can't find href in file using regular expression,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))"
"In Python, why won't something print without a newline?",sys.stdout.flush()
How to get a random value in python dictionary,"country, capital = random.choice(list(d.items()))"
Is there a function in python to split a word into a list?,list('Word to Split')
Regex: How to match words without consecutive vowels?,"[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]"
Using a RegEx to match IP addresses in Python,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')"
How to execute a file within the python interpreter?,"exec(compile(open('filename.py').read(), 'filename.py', 'exec'))"
Returning distinct rows in SQLAlchemy with SQLite,session.query(Tag).distinct(Tag.name).group_by(Tag.name).count()
Remove NULL columns in a dataframe Pandas?,"df = df.dropna(axis=1, how='all')"
Python counting elements of a list within a list,all(x.count(1) == 3 for x in L)
Comparing elements between elements in two lists of tuples,[x[0] for x in l1 if any(x[0] == y[0] for y in l2)]
how to clear/delete the Textbox in tkinter python on Ubuntu,"tex.delete('1.0', END)"
Python convert long to date,datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S')
How can I start a Python thread FROM C++?,system('python myscript.py')
sorting a list with objects of a class as its items,your_list.sort(key=operator.attrgetter('anniversary_score'))
sorting a list with objects of a class as its items,your_list.sort(key=lambda x: x.anniversary_score)
How can I convert a tensor into a numpy array in TensorFlow?,"print(type(tf.Session().run(tf.constant([1, 2, 3]))))"
"in Python, How to join a list of tuples into one list?",list(itertools.chain(*a))
How do I pythonically set a value in a dictionary if it is None?,"count.setdefault('a', 0)"
Python Pandas : group by in group by and average?,df.groupby(['cluster']).mean()
"from list of integers, get number closest to a given value","min(myList, key=lambda x: abs(x - myNumber))"
Find array item in a string,any(x in string for x in search)
Find string with regular expression in python,print(pattern.search(url).group(1))
"How do I convert all strings (like ""Fault"") and into a unique float?",(s.factorize()[0] + 1).astype('float')
Subtract values in one list from corresponding values in another list - Python,"C = [(a - b) for a, b in zip(A, B)]"
How to derive the week start for a given (iso) weeknumber / year in python,"datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')"
Python: How do I convert an array of strings to an array of numbers?,"map(int, ['1', '-1', '1'])"
"How to create datetime object from ""16SEP2012"" in python","datetime.datetime.strptime('16Sep2012', '%d%b%Y')"
How do I use a dictionary to update fields in Django models?,Book.objects.filter(pk=pk).update(**d)
How do I use a dictionary to update fields in Django models?,Book.objects.create(**d)
Precision in python,print('{0:.2f}'.format(your_number))
Python: How to generate a 12-digit random number?,"random.randint(100000000000, 999999999999)"
Python: How to generate a 12-digit random number?,"int(''.join(str(random.randint(0, 9)) for _ in range(12)))"
Python: How to generate a 12-digit random number?,""""""""""""".join(str(random.randint(0, 9)) for _ in range(12))"
Python: How to generate a 12-digit random number?,"'%0.12d' % random.randint(0, 999999999999)"
How to remove specific elements in a numpy array,"numpy.delete(a, index)"
Sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])"
read a single character from the user,sys.stdin.read(1)
How to get a list of matchable characters from a regex class,"print(re.findall(pattern, x))"
how to get the context of a search in BeautifulSoup?,k = soup.find(text=re.compile('My keywords')).parent.text