text
stringlengths
4
1.08k
What is the easiest way to convert list with str into list with int?,[int(i) for i in str_list]
What is the easiest way to convert list with str into list with int?,"map(int, ['1', '2', '3'])"
What is the easiest way to convert list with str into list with int?,"list(map(int, ['1', '2', '3']))"
Python BeautifulSoup Extract specific URLs,"soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/'))"
Python BeautifulSoup Extract specific URLs,"soup.find_all('a', href=re.compile('^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))"
Python: How can I execute a jar file through a python script,"subprocess.call(['java', '-jar', 'Blender.jar'])"
How can I insert NULL data into MySQL database with Python?,"cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,))"
remove a substring from the end of a string,"if url.endswith('.com'):
url = url[:(-4)]"
remove a substring from the end of a string,"url = re.sub('\\.com$', '', url)"
remove a substring from the end of a string,"print(url.replace('.com', ''))"
remove a substring from the end of a string,"if (not text.endswith(suffix)):
return text
return text[:(len(text) - len(suffix))]"
Python - print tuple elements with no brackets,"print(', ,'.join([str(i[0]) for i in mytuple]))"
Clamping floating numbers in Python?,"max(min(my_value, max_value), min_value)"
Splitting a string into words and punctuation,"re.findall('\\w+|[^\\w\\s]', text, re.UNICODE)"
How to execute raw SQL in SQLAlchemy-flask app,result = db.engine.execute('<sql here>')
Is there a method that tells my program to quit?,sys.exit(0)
Python - find digits in a string,""""""""""""".join(c for c in my_string if c.isdigit())"
python split string based on regular expression,"re.split(' +', str1)"
python split string based on regular expression,"re.findall('\\S+', str1)"
Python: How to get attribute of attribute of an object with getattr?,"getattr(getattr(myobject, 'id', None), 'number', None)"
Convert generator object to a dictionary,{i: (i * 2) for i in range(10)}
Convert generator object to a dictionary,"dict((i, i * 2) for i in range(10))"
How do I tell matplotlib that I am done with a plot?,plt.cla()
Python Convert String Literal to Float,"total = sum(float(item) for item in s.split(','))"
Python ASCII to binary,bin(ord('P'))
Get a string after a specific substring,"print(my_string.split(', ', 1)[1])"
Python Accessing Nested JSON Data,print(data['places'][0]['post code'])
Python RegEx using re.sub with multiple patterns,"word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\1\\2', word)"
How to extract data from JSON Object in Python?,"json.loads('{""foo"": 42, ""bar"": ""baz""}')['bar']"
Convert JSON array to Python list,data = json.loads(array)
Convert JSON array to Python list,data = json.loads(array)
Parsing a tweet to extract hashtags into an array in Python,"re.findall('#(\\w+)', 'http://example.org/#comments')"
Python - Fastest way to check if a string contains specific characters in any of the items in a list,any(e in lestring for e in lelist)
How to plot two columns of a pandas data frame using points?,"df.plot(x='col_name_1', y='col_name_2', style='o')"
Parsing HTML,"parsed_html = BeautifulSoup(html)
print(parsed_html.body.find('div', attrs={'class': 'container', }).text)"
Parsing HTML,"page = urllib.request.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)"
change figure size and figure format in matplotlib,"plt.figure(figsize=(3, 4))"
Best way to strip punctuation from a string in Python,"s.translate(None, string.punctuation)"
Django urlsafe base64 decoding with decryption,base64.urlsafe_b64decode(uenc.encode('ascii'))
Get the number of all keys in a dictionary of dictionaries in Python,len(dict_test) + sum(len(v) for v in dict_test.values())
Python convert decimal to hex,hex(d).split('x')[1]
converting integer to list in python,list(str(123))
converting integer to list in python,[int(x) for x in str(num)]
Python Mechanize select a form with no name,br.select_form(nr=0)
Python load json file with UTF-8 BOM header,"json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))"
Python load json file with UTF-8 BOM header,json.loads(open('sample.json').read().decode('utf-8-sig'))
Issue sending email with python?,"server = smtplib.SMTP('smtp.gmail.com', 587)"
Reversing bits of Python integer,"int('{:08b}'.format(n)[::-1], 2)"
Pandas DataFrame Add column to index without resetting,"df.set_index(['d'], append=True)"
Iterating over dictionaries using for loops,"for (key, value) in d.items():
pass"
Iterating over dictionaries using for loops,"for (key, value) in list(d.items()):
pass"
Iterating over dictionaries using for loops,"for (letter, number) in list(d.items()):
pass"
Iterating over dictionaries using for loops,"for (k, v) in list(d.items()):
pass"
Iterating over dictionaries using for loops,list(d.items())
Iterating over dictionaries using for loops,list(d.items())
Iterating over dictionaries using for loops,"for (k, v) in list(d.items()):
pass"
Iterating over dictionaries using for loops,"for (letter, number) in list(d.items()):
pass"
Iterating over dictionaries using for loops,"for (letter, number) in list(d.items()):
pass"
How do I implement a null coalescing operator in SQLAlchemy?,session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all()
How do I compile a Visual Studio project from the command-line?,os.system('msbuild project.sln /p:Configuration=Debug')
Get max key in dictionary,"max(list(MyCount.keys()), key=int)"
Can I use an alias to execute a program from a python script,os.system('source .bashrc; shopt -s expand_aliases; nuke -x scriptPath')
How to get a function name as a string in Python?,my_function.__name__
How to get a function name as a string in Python?,my_function.__name__
How to check if all values in the columns of a numpy matrix are the same?,"np.all(a == a[(0), :], axis=0)"
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]))"
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(a, key=lambda x: (sum(x[1:3]), x[0]), reverse=True)"
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]))"
Sorting a list of tuples by the addition of second and third element of the tuple,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)"
Add headers in a Flask app with unicode_literals,"response.headers['WWW-Authenticate'] = 'Basic realm=""test""'"
"In Django, how do I clear a sessionkey?",del request.session['mykey']
Python date string to date object,"datetime.datetime.strptime('24052010', '%d%m%Y').date()"
Replace non-ASCII characters with a single space,"re.sub('[^\\x00-\\x7F]+', ' ', text)"
List of lists into numpy array,"numpy.array([[1, 2], [3, 4]])"
What does a for loop within a list do in Python?,myList = [i for i in range(10)]
using regular expression to split string in python,[m[0] for m in re.compile('((.+?)\\2+)').findall('44442(2)2(2)44')]
using regular expression to split string in python,"[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]"
How to remove the space between subplots in matplotlib.pyplot?,"fig.subplots_adjust(wspace=0, hspace=0)"
How to reverse tuples in Python?,x[::-1]
Python JSON encoding,"json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})"
Writing List of Strings to Excel CSV File in Python,csvwriter.writerow(row)
How to convert datetime to string in python in django,{{(item.date | date): 'Y M d'}}
Non-consuming regular expression split in Python,"re.split('(?<=[\\.\\?!]) ', text)"
UTF in Python Regex,re.compile('\xe2\x80\x93')
declare an array,variable = []
declare an array,intarray = array('i')
How to reverse the elements in a sublist?,[sublist[::-1] for sublist in to_reverse[::-1]]
Replace all non-alphanumeric characters in a string,"re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')"