text
stringlengths
4
1.08k
Limit the number of sentences in a string,"re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)"
Split string into strings of repeating elements,"print([a for a, b in re.findall('((\\w)\\2*)', s)])"
How does this function to remove duplicate characters from a string in python work?,print(' '.join(OrderedDict.fromkeys(s)))
How does this function to remove duplicate characters from a string in python work?,print(' '.join(set(s)))
How can i list only the folders in zip archive in Python?,[x for x in file.namelist() if x.endswith('/')]
How to find the count of a word in a string?,input_string.count('Hello')
Python: reduce (list of strings) -> string,print('.'.join([item[0] for item in data]))
Dumping subprcess output in a file in append mode,fh1.seek(2)
list of ints into a list of tuples python,"print(zip(my_list[0::2], my_list[1::2]))"
list of ints into a list of tuples python,"my_new_list = zip(my_list[0::2], my_list[1::2])"
"How to fix: ""UnicodeDecodeError: 'ascii' codec can't decode byte""",sys.setdefaultencoding('utf8')
Python datetime to string without microsecond component,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
How to retrieve only arabic texts from a string using regular expression?,"print(re.findall('[\\u0600-\\u06FF]+', my_string))"
How to group DataFrame by a period of time?,df.groupby(df.index.map(lambda t: t.minute))
Accessing elements of python dictionary,dict['Apple']['American']
How to remove rows with null values from kth column onward in python,"df2.dropna(subset=['three', 'four', 'five'], how='all')"
How do I insert a list at the front of another list?,"a.insert(0, k)"
How do I insert a list at the front of another list?,a = a[:n] + k + a[n:]
Pyhon - Best way to find the 1d center of mass in a binary numpy array,np.flatnonzero(x).mean()
Keep only date part when using pandas.to_datetime,df['just_date'] = df['dates'].dt.date
Removing one list from another,[x for x in a if x not in b]
How do I transform a multi-level list into a list of strings in Python?,[''.join(x) for x in a]
How do I transform a multi-level list into a list of strings in Python?,"list(map(''.join, a))"
Matching blank lines with regular expressions,"re.split('\n\\s*\n', s)"
Merging items in a list - Python,"from functools import reduce
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])"
Convert float to comma-separated string,"""""""{0:,.2f}"""""".format(24322.34)"
How to pass dictionary items as function arguments in python?,my_function(**data)
get line count,sum((1 for line in open('myfile.txt')))
How to round integers in python,"print(round(1123.456789, -1))"
Sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]"
Sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]"
How to get week number in Python?,"datetime.date(2010, 6, 16).isocalendar()[1]"
Select multiple ranges of columns in Pandas DataFrame,"df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]"
Python Pandas: Multiple aggregations of the same column,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})"
convert string to lowercase,s.lower()
convert string to lowercase,s.decode('utf-8').lower()
How to download a file via FTP with Python ftplib,"ftp.retrbinary('RETR %s' % filename, file.write)"
How do I increase the timeout for imaplib requests?,"urlfetch.fetch(url, deadline=10 * 60)"
Output first 100 characters in a string,print(my_string[0:100])
matplotlib Legend Markers Only Once,legend(numpoints=1)
Python - How to calculate equal parts of two dictionaries?,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())"
load csv into 2D matrix with numpy for plotting,"numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)"
Django database query: How to filter objects by date range?,"Sample.objects.filter(date__range=['2011-01-01', '2011-01-31'])"
Django database query: How to filter objects by date range?,"Sample.objects.filter(date__year='2011', date__month='01')"
syntax for creating a dictionary into another dictionary in python,"d['dict3'] = {'spam': 5, 'ham': 6}"
How to apply numpy.linalg.norm to each row of a matrix?,"numpy.apply_along_axis(numpy.linalg.norm, 1, a)"
How to merge two Python dictionaries in a single expression?,"dict((k, v) for d in dicts for k, v in list(d.items()))"
Python. Convert escaped utf string to utf-string,print('your string'.decode('string_escape'))
Counting the number of True Booleans in a Python List,"sum([True, True, False, False, False, True])"
Matplotlib.animation: how to remove white margin,"fig.set_size_inches(w, h, forward=True)"
python string format() with dict with integer keys,'hello there %(5)s' % {'5': 'you'}
Python - converting a string of numbers into a list of int,"map(int, example_string.split(','))"
Python - converting a string of numbers into a list of int,"[int(s) for s in example_string.split(',')]"
Python list of tuples to list of int,x = [i[0] for i in x]
Python list of tuples to list of int,"y = map(operator.itemgetter(0), x)"
Python list of tuples to list of int,y = [i[0] for i in x]
How do I extract all the values of a specific key from a list of dictionaries?,results = [item['value'] for item in test_data]
ISO Time (ISO 8601) in Python,datetime.datetime.now().isoformat()
ISO Time (ISO 8601) in Python,datetime.datetime.utcnow().isoformat()
Merging data frame columns of strings into one single column in Pandas,"df.apply(' '.join, axis=0)"
pandas Subtract Dataframe with a row from another dataframe,"pd.DataFrame(df.values - df2.values, columns=df.columns)"
How can I detect DOS line breaks in a file?,"print(open('myfile.txt', 'U').read())"
Python - read text file with weird utf-16 format,print(line.decode('utf-16-le').split())
Python - read text file with weird utf-16 format,"file = io.open('data.txt', 'r', encoding='utf-16-le')"
Finding common rows (intersection) in two Pandas dataframes,"s1 = pd.merge(df1, df2, how='inner', on=['user_id'])"
How can I check a Python unicode string to see that it *actually* is proper Unicode?,foo.decode('utf8').encode('utf8')
Numpy array dimensions,a.shape
Numpy array dimensions,N.shape(a)
Numpy array dimensions,N.shape(a)
Numpy array dimensions,a.shape
How to search a list of tuples in Python,"[i for i, v in enumerate(L) if v[0] == 53]"
convert a string of bytes into an int (python),"struct.unpack('<L', 'y\xcc\xa6\xbb')[0]"
How to get the values from a NumPy array using multiple indices,"arr[[0, 1, 1], [1, 0, 2]]"
what's a good way to combinate through a set?,list(powerset('abcd'))
Converting from a string to boolean in Python?,"s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']"
How do I url encode in Python?,urllib.parse.quote('http://spam.com/go/')
How can I get the output of a matplotlib plot as an SVG?,plt.savefig('test.svg')
Counting array elements in Python,len(myArray)
Python Embedding in C++ : ImportError: No module named pyfunction,"sys.path.insert(0, './path/to/your/modules/')"
How to plot with x-axis at the top of the figure?,ax.xaxis.set_ticks_position('top')
Python - Bulk Select then Insert from one DB to another,cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1')
How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*\\Z', 'A\n')"
How do I use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', '!A_B')"
Convert hex string to int,"int('deadbeef', 16)"
Convert hex string to int,"int('a', 16)"
Convert hex string to int,"int('0xa', 16)"
Convert hex string to int,"int(s, 16)"
Convert hex string to int,"int(hexString, 16)"
How to print variables without spaces between values,"print('Value is ""' + str(value) + '""')"
How to print variables without spaces between values,"print('Value is ""{}""'.format(value))"
How do I convert an array to string using the jinja template engine?,{{tags | join(' ')}}
get a list of locally installed Python modules,help('modules')
Slicing a multidimensional list,[[[x[0]] for x in listD[i]] for i in range(len(listD))]
Sort a string in lexicographic order python,"sorted(s, key=str.upper)"
Sort a string in lexicographic order python,"sorted(sorted(s), key=str.upper)"
Sort a string in lexicographic order python,"sorted(s, key=str.lower)"
Compare Python Pandas DataFrames for matching rows,"pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner')"
get keys correspond to a value in dictionary,"dict((v, k) for k, v in map.items())"
How to decode unicode raw literals to readable string?,s.decode('unicode_escape')