text
stringlengths
4
1.08k
Trimming a string,myString.lstrip('\n\r')
Trimming a string,myString.rstrip('\n\t')
Trimming a string,' Hello\n'.strip(' ')
Sort a list of tuples depending on two elements,"sorted(unsorted, key=lambda element: (element[1], element[2]))"
"Python, Encoding output to UTF-8",print(content.decode('utf8'))
How do I vectorize this loop in numpy?,"np.ma.array(np.tile(arr, 2).reshape(2, 3), mask=~cond).argmax(axis=1)"
How to convert efficiently a dataframe column of string type into datetime in Python?,pd.to_datetime(df.ID.str[1:-3])
How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?,"df = pd.read_csv('my.csv', dtype={'my_column': np.float64}, na_values=['n/a'])"
How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?,"df = pd.read_csv('my.csv', na_values=['n/a'])"
All combinations of a list of lists,list(itertools.product(*a))
How to extract all UPPER from a string? Python,"re.sub('[^A-Z]', '', s)"
Get date from ISO week number in Python,"datetime.strptime('2011221', '%Y%W%w')"
"How to read a ""C source, ISO-8859 text""","codecs.open('myfile', 'r', 'iso-8859-1').read()"
List Comprehensions in Python : efficient selection in a list,[f(x) for x in list]
Regex matching 5-digit substrings not enclosed with digits,"re.findall('(?<!\\d)\\d{5}(?!\\d)', s)"
filtering elements from list of lists in Python?,[item for item in a if sum(item) > 10]
python: how to convert currency to decimal?,cents_int = int(round(float(dollars.strip('$')) * 100))
Remove final characters from string recursively - What's the best way to do this?,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]"
Creating an empty list,l = []
Creating an empty list,l = list()
Creating an empty list,list()
Creating an empty list,[]
How to properly quit a program in python,sys.exit(0)
Add string in a certain position in Python,s[:4] + '-' + s[4:]
Python : how to append new elements in a list of list?,[[] for i in range(3)]
Python : how to append new elements in a list of list?,a = [[] for i in range(3)]
Changing the referrer URL in python requests,"requests.get(url, headers={'referer': my_referer})"
"Python, Matplotlib, subplot: How to set the axis range?","pylab.ylim([0, 1000])"
Pandas convert a column of list to dummies,pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0)
Finding the largest delta between two integers in a list in python,"max(abs(x - y) for x, y in zip(values[1:], values[:-1]))"
How to convert hex string to integer in Python?,"y = str(int(x, 16))"
check if a string is a number (float),a.isdigit()
check if a string is a number,isdigit()
check if a string is a number,b.isdigit()
pandas.read_csv: how to skip comment lines,"pd.read_csv(StringIO(s), sep=',', comment='#')"
Pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
sum a list of numbers in Python,sum(list_of_nums)
how to get the index of dictionary with the highest value in a list of dictionary,"max(lst, key=lambda x: x['score'])"
Get data from the meta tags using BeautifulSoup,soup.findAll(attrs={'name': 'description'})
Python: how to get rid of spaces in str(dict)?,"str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')"
Python: how to get rid of spaces in str(dict)?,"'{' + ','.join('{0!r}:{1!r}'.format(*x) for x in list(dct.items())) + '}'"
Python- insert a character into a string,""""""""""""".join(parts[1:])"
Python- insert a character into a string,""""""",+"""""".join(c.rsplit('+', 1))"
How do I delete a row in a numpy array which contains a zero?,"a[np.all(a != 0, axis=1)]"
Extracting only characters from a string in Python,""""""" """""".join(re.split('[^a-zA-Z]*', 'your string'))"
Extracting only characters from a string in Python,"re.split('[^a-zA-Z]*', 'your string')"
Create Union of All Values Contained in Multiple Lists,results_union = set().union(*results_list)
Create Union of All Values Contained in Multiple Lists,return list(set(itertools.chain(*result_list)))
python: check if an numpy array contains any element of another array,"np.any(np.in1d(a1, a2))"
Removing control characters from a string in python,return ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'C')
How to compare two lists in python,"all(i < j for i, j in zip(a, b))"
python selenium click on button,driver.find_element_by_css_selector('.button.c_button.s_button').click()
python selenium click on button,driver.find_element_by_css_selector('.button .c_button .s_button').click()
Is it possible to kill a process on Windows from within Python?,os.system('taskkill /im make.exe')
How to get current date and time from DB using SQLAlchemy,"print(select([my_table, func.current_date()]).execute())"
Remove duplicate chars using regex?,"re.sub('([a-z])\\1+', '\\1', 'ffffffbbbbbbbqqq')"
Regex to remove periods in acronyms?,"re.sub('(?<!\\w)([A-Z])\\.', '\\1', s)"
how to parse a list or string into chunks of fixed length,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]"
replacing all regex matches in single line,"re.sub('\\b(this|string)\\b', '<markup>\\1</markup>', 'this is my string')"
Output data from all columns in a dataframe in pandas,"pandas.set_option('display.max_columns', 7)"
Output data from all columns in a dataframe in pandas,"pandas.set_option('display.max_columns', None)"
Modifying a subset of rows in a pandas dataframe,"df.ix[df.A == 0, 'B'] = np.nan"
Selecting Element followed by text with Selenium WebDriver,"driver.find_element_by_xpath(""//li/label/input[contains(..,'polishpottery')]"")"
Ordering a list of dictionaries in python,"mylist.sort(key=operator.itemgetter('weight', 'factor'))"
Ordering a list of dictionaries in python,"mylist.sort(key=lambda d: (d['weight'], d['factor']))"
From a list of lists to a dictionary,{x[1]: x for x in lol}
Sorting dictionary keys based on their values,"sorted(d, key=lambda k: d[k][1])"
Python: How to round 123 to 100 instead of 100.0?,"int(round(123, -2))"
How do I create a file in python without overwriting an existing file,"fd = os.open('x', os.O_WRONLY | os.O_CREAT | os.O_EXCL)"
How to slice a list of strings with space delimiter?,new_list = [x.split()[-1] for x in Original_List]
Reverse a string,'hello world'[::(-1)]
Reverse a string,s[::(-1)]
Reverse a string,''.join(reversed('foo'))
Reverse a string,''.join(reversed(string))
Reverse a string,'foo'[::(-1)]
Reverse a string,a_string[::(-1)]
Reverse a string,"def reversed_string(a_string):
return a_string[::(-1)]"
Reverse a string,''.join(reversed(s))
Generate a sequence of numbers in Python,""""""","""""".join(str(i) for i in range(100) if i % 4 in (1, 2))"
How to convert this list into a dictionary,"dict([(e[0], int(e[1])) for e in lst])"
sorting a list of tuples in Python,"sorted(list_of_tuples, key=lambda tup: tup[::-1])"
sorting a list of tuples in Python,"sorted(list_of_tuples, key=lambda tup: tup[1])"
Concatenating two one-dimensional NumPy arrays,"numpy.concatenate([a, b])"
Writing a list to a file with Python,"for item in thelist:
thefile.write(('%s\n' % item))"
Writing a list to a file with Python,"for item in thelist:
pass"
Writing a list to a file with Python,"pickle.dump(itemlist, outfile)"
Writing a list to a file with Python,outfile.write('\n'.join(itemlist))
SQLAlchemy: a better way for update with declarative?,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'})
How to send cookies in a post request with the Python Requests library?,"r = requests.post('http://wikipedia.org', cookies=cookie)"
How to include third party Python libraries in Google App Engine?,"sys.path.insert(0, 'libs')"
get current time,datetime.datetime.now()
get current time,datetime.datetime.now().time()
get current time,"strftime('%Y-%m-%d %H:%M:%S', gmtime())"
get current time,str(datetime.now())
get current time,datetime.datetime.time(datetime.datetime.now())
Converting hex to int in python,ord('\xff')
Python Pandas Identify Duplicated rows with Additional Column,"df.groupby(['PplNum', 'RoomNum']).cumcount() + 1"