text stringlengths 4 1.08k |
|---|
remove (chomp) a newline,s.rstrip() |
remove (chomp) a newline,s.lstrip() |
remove (chomp) a newline,'Mac EOL\r'.rstrip('\r\n') |
remove (chomp) a newline,'Windows EOL\r\n'.rstrip('\r\n') |
remove (chomp) a newline,'Unix EOL\n'.rstrip('\r\n') |
remove (chomp) a newline,'Hello\n\n\n'.rstrip('\n') |
Python - split sentence after words but with maximum of n characters in result,"re.findall('.{,16}\\b', text)" |
NumPy List Comprehension Syntax,[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))] |
Convert unicode string to byte string,'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1') |
Best way to split a DataFrame given an edge,df.groupby((df.a == 'B').shift(1).fillna(0).cumsum()) |
Save JSON outputed from a URL to a file,"urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')" |
Find indices of elements equal to zero from numpy array,numpy.where((x == 0))[0] |
"python, subprocess: reading output from subprocess",sys.stdout.flush() |
Converting integer to string,str(i) |
Converting integer to string,a.__str__() |
Converting integer to string,str(a) |
Method to sort a list of lists?,L.sort(key=operator.itemgetter(1)) |
How do I add space between two variables after a print in Python,print(str(count) + ' ' + str(conv)) |
Pandas changing cell values based on another cell,"df.fillna(method='ffill', inplace=True)" |
Is there a way to make the Tkinter text widget read only?,text.config(state=DISABLED) |
Python sum of ASCII values of all characters in a string,"sum(map(ord, string))" |
How to apply itertools.product to elements of a list of lists?,list(itertools.product(*arrays)) |
print number with commas as thousands separators,"'{:,}'.format(value)" |
print number with commas as thousands separators,"locale.setlocale(locale.LC_ALL, 'en_US') |
locale.format('%d', 1255000, grouping=True)" |
"How to pass through a list of queries to a pandas dataframe, and output the list of results?","df[df.Col1.isin(['men', 'rocks', 'mountains'])]" |
Accessing a value in a tuple that is in a list,[x[1] for x in L] |
splitting unicode string into words,'\u0440\u0430\u0437 \u0434\u0432\u0430 \u0442\u0440\u0438'.split() |
Django - How to sort queryset by number of character in a field,MyModel.objects.extra(select={'length': 'Length(name)'}).order_by('length') |
Python - Choose a dictionary in list which key is closer to a global value,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))" |
Finding missing values in a numpy array,m[~m.mask] |
Use of findall and parenthesis in Python,"re.findall('\\b[A-Z]', formula)" |
How to define two-dimensional array in python,matrix = [([0] * 5) for i in range(5)] |
Creating a numpy array of 3D coordinates from three 1D arrays,"np.vstack(np.meshgrid(x_p, y_p, z_p)).reshape(3, -1).T" |
How to find the minimum value in a numpy matrix?,arr[arr != 0].min() |
Python Selenium: Find object attributes using xpath,"browser.find_elements_by_xpath(""//*[@type='submit']/@value"").text" |
Python Selenium: Find object attributes using xpath,"browser.find_elements_by_xpath(""//*[@type='submit']"").get_attribute('value')" |
parse a YAML file,"with open('example.yaml', 'r') as stream: |
print((yaml.load(stream)))" |
How to swap a group of column headings with their values in Pandas,"pd.DataFrame(df.columns[np.argsort(df.values)], df.index, np.unique(df.values))" |
Getting today's date in YYYY-MM-DD in Python?,datetime.datetime.today().strftime('%Y-%m-%d') |
How to urlencode a querystring in Python?,urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$') |
python sorting dictionary by length of values,"print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))" |
convert list of tuples to multiple lists in Python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" |
convert list of tuples to multiple lists in Python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))" |
convert list of tuples to multiple lists in Python,"zip(*[(1, 2), (3, 4), (5, 6)])" |
Create a list of tuples with adjacent list elements if a condition is true,"[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]" |
How can i set proxy with authentication in selenium chrome web driver using python,driver.get('http://www.google.com.br') |
Python reversing an UTF-8 string,b = a.decode('utf8')[::-1].encode('utf8') |
Extracting date from a string in Python,"dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)" |
Extracting date from a string in Python,"dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)" |
Extracting date from a string in Python,"dparser.parse('monkey 10/01/1980 love banana', fuzzy=True)" |
Efficient way to convert a list to dictionary,"dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))" |
How can I check if a string contains ANY letters from the alphabet?,"re.search('[a-zA-Z]', the_string)" |
Converting a Pandas GroupBy object to DataFrame,"DataFrame({'count': df1.groupby(['Name', 'City']).size()}).reset_index()" |
Removing all non-numeric characters from string in Python,"re.sub('[^0-9]', '', 'sdkjh987978asd098as0980a98sd')" |
List comprehension with if statement,[y for y in a if y not in b] |
How to subset a dataset in pandas dataframe?,df.groupby('ID').head(4) |
How to unzip a list of tuples into individual lists?,zip(*l) |
How do I combine two lists into a dictionary in Python?,"dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
How do I combine two lists into a dictionary in Python?,"dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
How do I get the different parts of a Flask request's url?,request.url |
How to remove ^M from a text file and replace it with the next line,"somestring.replace('\\r', '')" |
Best way to encode tuples with json,"simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))" |
Converting string into datetime,"datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')" |
Converting string into datetime,parser.parse('Aug 28 1999 12:00AM') |
Python - Extract folder path from file path,os.path.split(os.path.abspath(existGDBPath)) |
Python - Extract folder path from file path,os.path.dirname(os.path.abspath(existGDBPath)) |
Post JSON using Python Requests,"requests.post('http://httpbin.org/post', json={'test': 'cheers'})" |
Python - Remove dictionary from list if key is equal to value,a = [x for x in a if x['link'] not in b] |
Getting a request parameter in Jinja2,{{request.args.get('a')}} |
Python - Create list with numbers between 2 values?,"list(range(11, 17))" |
type conversion in python from int to float,data_df['grade'] = data_df['grade'].astype(float).astype(int) |
Sorting or Finding Max Value by the second element in a nested list. Python,"max(alkaline_earth_values, key=lambda x: x[1])" |
How to remove leading and trailing zeros in a string? Python,your_string.strip('0') |
Generating all unique pair permutations,"list(permutations(list(range(9)), 2))" |
Python regular expression matching a multiline block of text,"re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)" |
Python regular expression matching a multiline block of text,"re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)" |
How do you call a python file that requires a command line argument from within another python file?,"call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])" |
Sort a multidimensional list by a variable number of keys,"a.sort(key=operator.itemgetter(2, 3))" |
Add another tuple to a tuple,"final_choices = ((another_choice,) + my_choices)" |
Add another tuple to a tuple,"final_choices = ((another_choice,) + my_choices)" |
Find current directory and file's directory,os.getcwd() |
Find current directory and file's directory,os.path.realpath(__file__) |
Find current directory and file's directory,os.path.dirname(path) |
Find current directory and file's directory,os.path.realpath(path) |
Find current directory,dir_path = os.path.dirname(os.path.realpath(__file__)) |
Find current directory,cwd = os.getcwd() |
Find current directory,full_path = os.path.realpath(__file__) |
Sort numpy matrix row values in ascending order,"arr[arr[:, (2)].argsort()]" |
Sort numpy matrix row values in ascending order,"numpy.sort(arr, axis=0)" |
split string on a number of different characters,"re.split('[ .]', 'a b.c')" |
copying one file's contents to another in python,"shutil.copy('file.txt', 'file2.txt')" |
What's the best way to generate random strings of a specific length in Python?,print(''.join(choice(ascii_uppercase) for i in range(12))) |
How to merge the elements in a list sequentially in python,"[''.join(seq) for seq in zip(lst, lst[1:])]" |
python: rename single column header in pandas dataframe,"data.rename(columns={'gdp': 'log(gdp)'}, inplace=True)" |
Converting html to text with Python,print(soup.get_text()) |
python: sort a list of lists by an item in the sublist,"sorted(li, key=operator.itemgetter(1), reverse=True)" |
Pandas - replacing column values,"data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)" |
Regex punctuation split [Python],"re.split('\\W+', 'Words, words, words.')" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.