neulab/docprompting-conala huggingface dataset:
# Display maximum output data of columns in dataframe `pandas` that will fit into the screen
pandas.set_option('display.max_columns', None)
# sort list `the_list` by the length of string followed by alphabetical order
the_list.sort(key=lambda item: (-len(item), item))
# convert list `a` from being consecutive sequences of tuples into a single sequence of elements
list(itertools.chain(*a))
# convert a flat list into a list of tuples of every two items in the list, in order
print(zip(my_list[0::2], my_list[1::2]))
# group a list of ints into a list of tuples of each 2 elements
my_new_list = zip(my_list[0::2], my_list[1::2])
# Slice `url` with '&' as delimiter  to get  "http://www.domainname.com/page?CONTENT_ITEM_ID=1234" from url "http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3
"
url.split('&')
# convert python dictionary `your_data` to json array
json.dumps(your_data, ensure_ascii=False)
# retrieve arabic texts from string `my_string`
print(re.findall('[\\u0600-\\u06FF]+', my_string))
# sort list `L` based on the value of variable 'resultType' for each object in list `L`
sorted(L, key=operator.itemgetter('resultType'))
# sort a list of objects `s` by a member variable 'resultType'
s.sort(key=operator.attrgetter('resultType'))
# sort a list of objects 'somelist' where the object has member number variable `resultType`
somelist.sort(key=lambda x: x.resultType)
# parse a YAML file "example.yaml"
with open('example.yaml', 'r') as stream:
    try:
        print((yaml.load(stream)))
    except yaml.YAMLError as exc:
        print(exc)
# parse a YAML file "example.yaml"
with open('example.yaml') as stream:
    try:
        print((yaml.load(stream)))
    except yaml.YAMLError as exc:
        print(exc)
# split string `s` into float values and write sum to `total`
total = sum(float(item) for item in s.split(','))
# substitute occurrences of unicode regex pattern u'\\p{P}+' with empty string '' in string `text`
return re.sub('\\p{P}+', '', text)
# access value associated with key 'American' of key 'Apple' from dictionary `dict`
dict['Apple']['American']
# Python date string formatting
"""{0.month}/{0.day}/{0.year}""".format(my_date)
# find rows with non zero values in a subset of columns where `df.dtypes` is not equal to `object` in pandas dataframe
df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]
# check if all elements in a tuple `(1, 6)` are in another `(1, 2, 3, 4, 5)`
all(i in (1, 2, 3, 4, 5) for i in (1, 6))
# Get a list `C` by subtracting values in one list `B` from corresponding values in another list `A`
C = [(a - b) for a, b in zip(A, B)]
# pull a value with key 'name' from a json object `item`
print(item['name'])
# removing vowel characters 'aeiouAEIOU' from string `text`
"""""".join(c for c in text if c not in 'aeiouAEIOU')
# get last element of string splitted by '\\' from list of strings `list_dirs`
[l.split('\\')[-1] for l in list_dirs]
# reverse a UTF-8 string 'a'
b = a.decode('utf8')[::-1].encode('utf8')
# find all occurrences of regex pattern '(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)' in string `x`
re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)
# Return rows of data associated with the maximum value of column 'Value' in dataframe `df`
df.loc[df['Value'].idxmax()]
# Convert a datetime object `my_datetime` into readable format `%B %d, %Y`
my_datetime.strftime('%B %d, %Y')
# Sort items in dictionary `d`  using the first part of the key after splitting the key
sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))
# Execute a put request to the url `url`
response = requests.put(url, data=json.dumps(data), headers=headers)
# plot a data logarithmically in y axis
plt.yscale('log', nonposy='clip')
# build a dictionary containing the conversion of each list in list `[['two', 2], ['one', 1]]` to a key/value pair as its items
dict([['two', 2], ['one', 1]])
# convert list `l` to dictionary having each two adjacent elements as key/value pair
dict(zip(l[::2], l[1::2]))
# create list `c` containing items from list `b` whose index is in list `index`
c = [b[i] for i in index]
# get geys of dictionary `my_dict` that contain any values from list `lst`
[key for key, value in list(my_dict.items()) if set(value).intersection(lst)]
# get list of keys in dictionary `my_dict` whose values contain values from list `lst`
[key for item in lst for key, value in list(my_dict.items()) if item in value]
# get first non-null value per each row from dataframe `df`
df.stack().groupby(level=0).first()
# Update row values for a column `Season` using vectorized string operation in pandas
df['Season'].str.split('-').str[0].astype(int)
# find all digits in string '6,7)' and put them to a list
re.findall('\\d|\\d,\\d\\)', '6,7)')
# check if string `foo` is UTF-8 encoded
foo.decode('utf8').encode('utf8')
# check if  dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`
all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])
# Get only digits from a string `strs`
"""""".join([c for c in strs if c.isdigit()])
# sort dictionary `tag_weight` in reverse order by values cast to integers
sorted(list(tag_weight.items()), key=lambda x: int(x[1]), reverse=True)
# sort list `mylist` of tuples by arbitrary key from list `order`
sorted(mylist, key=lambda x: order.index(x[1]))
# multiply values of dictionary `dict` with their respective values in dictionary `dict2`
dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)
# insert directory 'libs' at the 0th index of current directory
sys.path.insert(0, 'libs')
# download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext'
urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')
# scroll to the bottom of a web page using selenium webdriver
driver.execute_script('window.scrollTo(0, Y)')
# scroll a to the bottom of a web page using selenium webdriver
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
# remove tags from a string `mystring`
re.sub('<[^>]*>', '', mystring)
# append array of strings `['x', 'x', 'x']` into one string
"""""".join(['x', 'x', 'x'])
# Find all the items from a dictionary `D` if the key contains the string `Light`
[(k, v) for k, v in D.items() if 'Light' in k]
# create a list `result` containing elements form list `list_a` if first element of list `list_a` is in list `list_b`
result = [x for x in list_a if x[0] in list_b]
# transforming the string `s` into dictionary
dict(map(int, x.split(':')) for x in s.split(','))
# set UTC offset by 9 hrs ahead for date '2013/09/11 00:17'
dateutil.parser.parse('2013/09/11 00:17 +0900')
# Return a subplot axes positioned by the grid definition `1,1,1` using matpotlib
fig.add_subplot(1, 1, 1)
# replace nan values in a pandas data frame with the average of columns
df.apply(lambda x: x.fillna(x.mean()), axis=0)
# sort dictionary of dictionaries `dic` according to the key 'Fisher'
sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)
# check if the string `myString` is empty
if (not myString):
    pass
# check if string `some_string` is empty
if (not some_string):
    pass
# check if string `my_string` is empty
if (not my_string):
    pass
# set font size of axis legend of plot `plt` to 'xx-small'
plt.setp(legend.get_title(), fontsize='xx-small')
# Get a list of  words from a string `Hello world, my name is...James the 2nd!` removing punctuation
re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')
# List all the files that doesn't contain the name `hello`
glob.glob('[!hello]*.txt')
# List all the files that matches the pattern `hello*.txt`
glob.glob('hello*.txt')
# upload binary file `myfile.txt` with ftplib
ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))
# convert and escape string "\\xc3\\x85あ" to UTF-8 code
"""\\xc3\\x85あ""".encode('utf-8').decode('unicode_escape')
# encode string "\\xc3\\x85あ" to bytes
"""\\xc3\\x85あ""".encode('utf-8')
# combine  dataframe `df1` and dataframe `df2` by index number
pd.merge(df1, df2, left_index=True, right_index=True, how='outer')
# Combine two Pandas dataframes with the same index
pandas.concat([df1, df2], axis=1)
# replace parentheses and all data within it with empty string '' in column 'name' of dataframe `df`
df['name'].str.replace('\\(.*\\)', '')
# delete items from list `my_list` if the item exist in list `to_dell`
my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
# invoke perl script './uireplace.pl' using perl interpeter '/usr/bin/perl' and send argument `var` to it
subprocess.call(['/usr/bin/perl', './uireplace.pl', var])
# filter lines from a text file 'textfile' which contain a word 'apple'
[line for line in open('textfile') if 'apple' in line]
# Check if the value of the key "name" is "Test" in a list of dictionaries `label`
any(d['name'] == 'Test' for d in label)
# get value in string `line` matched by regex pattern '\\bLOG_ADDR\\s+(\\S+)'
print(re.search('\\bLOG_ADDR\\s+(\\S+)', line).group(1))
# remove all null values from columns 'three', 'four' and 'five' of dataframe `df2`
df2.dropna(subset=['three', 'four', 'five'], how='all')
# insert variables `(var1, var2, var3)` into sql statement 'INSERT INTO table VALUES (?, ?, ?)'
cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))
# Execute a sql statement using variables `var1`, `var2` and `var3`
cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))
# How to use variables in SQL statement in Python?
cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))
# Selenium `driver` click a hyperlink with the pattern "a[href^='javascript']"
driver.find_element_by_css_selector("a[href^='javascript']").click()
# Print string `t` with proper unicode representations
print(t.decode('unicode_escape'))
# convert list `lst` of key, value pairs into a dictionary
dict([(e[0], int(e[1])) for e in lst])
# Print a string `card` with string formatting
print('I have: {0.price}'.format(card))
# None
datetime.datetime.strptime('2007-03-04T21:08:12', '%Y-%m-%dT%H:%M:%S')
# convert list of strings `str_list` into list of integers
[int(i) for i in str_list]
# convert a list with string `['1', '2', '3']` into list with integers
map(int, ['1', '2', '3'])
# convert list with str into list with int
list(map(int, ['1', '2', '3']))
# Return values for column `C` after group by on column `A` and `B` in dataframe `df`
df.groupby(['A', 'B'])['C'].unique()
# Add header `('Cookie', 'cookiename=cookie value')` to mechanize browser `br`
br.addheaders = [('Cookie', 'cookiename=cookie value')]
# execute a command `command ` in the terminal from a python script
os.system(command)
# attach debugger pdb to class `ForkedPdb`
ForkedPdb().set_trace()
# drop all columns in dataframe `df` that holds a maximum value bigger than 0
df.columns[df.max() > 0]
# concatenate lists `listone` and `listtwo`
(listone + listtwo)
# iterate items in lists `listone` and `listtwo`
for item in itertools.chain(listone, listtwo):
    pass
# convert date string `s` in format pattern '%d/%m/%Y' into a timestamp
time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())
# convert string '01/12/2011' to an integer timestamp
int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))
# move the last item in list `a` to the beginning
a = a[-1:] + a[:-1]
# Remove the string value `item` from a list of strings `my_sequence`
[item for item in my_sequence if item != 'item']
# print each first value from a list of tuples `mytuple` with string formatting
print(', ,'.join([str(i[0]) for i in mytuple]))
# Serialize dictionary `data` and its keys to a JSON formatted string
json.dumps({str(k): v for k, v in data.items()})
# remove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into floats
df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)
# insert spaces before capital letters in string `text`
re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text)
# Get all the sentences from a string `text` using regex
re.split('\\.\\s', text)
# Regular expression in Python sentence extractor
re.split('\\.\\s', re.sub('\\.\\s*$', '', text))
# convert a list 'a' to a dictionary where each even element represents the key to the dictionary, and the following odd element is the value
b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}
# replace value 0 with 'Female' and value 1 with 'Male' in column 'sex' of dataframe `data`
data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)
# convert date string 'January 11, 2010'  into day of week
datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')
# Convert Date String to Day of Week
datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')
# check if key 'stackoverflow' and key 'google' are presented in dictionary `sites`
set(['stackoverflow', 'google']).issubset(sites)
# convert unicode text from list `elems` with index 0 to normal text 'utf-8'
elems[0].getText().encode('utf-8')
# Convert a datetime object `dt` to microtime
time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
# check whether file "/path/to/file" exists
my_file = Path('/path/to/file')
if my_file.is_file():
    pass
# check whether file `file_path` exists
os.path.exists(file_path)
# check whether a file "/etc/password.txt" exists
print(os.path.isfile('/etc/password.txt'))
# check whether a file "/etc" exists
print(os.path.isfile('/etc'))
# check whether a path "/does/not/exist" exists
print(os.path.exists('/does/not/exist'))
# check whether a file "/does/not/exist" exists
print(os.path.isfile('/does/not/exist'))
# check whether a path "/etc/password.txt" exists
print(os.path.exists('/etc/password.txt'))
# print line `line` from text file with 'utf-16-le' format
print(line.decode('utf-16-le').split())
# open a text file `data.txt` in io module with encoding `utf-16-le`
file = io.open('data.txt', 'r', encoding='utf-16-le')
# create a list with the sum of respective elements of the tuples of list `l`
[sum(x) for x in zip(*l)]
# sum each value in a list `l` of tuples
map(sum, zip(*l))
# BeautifulSoup select 'div' elements with an id attribute value ending with sub-string '_answer' in HTML parsed string `soup`
soup.select('div[id$=_answer]')
# kill a process with id `process.pid`
os.kill(process.pid, signal.SIGKILL)
# Get Last Day of the first month in 2002
calendar.monthrange(2002, 1)
# Get Last Day of the second month in 2002
calendar.monthrange(2008, 2)
# Get Last Day of the second month in 2100
calendar.monthrange(2100, 2)
# Get Last Day of the month `month` in year `year`
calendar.monthrange(year, month)[1]
# Get Last Day of the second month in year 2012
monthrange(2012, 2)
# Get Last Day of the first month in year 2000
(datetime.date(2000, 2, 1) - datetime.timedelta(days=1))
# print the string `Total score for`, the value of the variable `name`, the string `is` and the value of the variable `score` in one print call.
print(('Total score for', name, 'is', score))
# print multiple arguments 'name' and 'score'.
print('Total score for {} is {}'.format(name, score))
# print a string using multiple strings `name` and `score`
print('Total score for %s is %s  ' % (name, score))
# print string including multiple variables `name` and `score`
print(('Total score for', name, 'is', score))
# print float `a` with two decimal points
print(('%.2f' % a))
# print float `a` with two decimal points
print(('{0:.2f}'.format(a)))
# print float `a` with two decimal points
print(('{0:.2f}'.format(round(a, 2))))
# print float `a` with two decimal points
print(('%.2f' % round(a, 2)))
# limit float 13.9499999 to two decimal points
('%.2f' % 13.9499999)
# limit float 3.14159 to two decimal points
('%.2f' % 3.14159)
# limit float 13.949999999999999 to two decimal points
float('{0:.2f}'.format(13.95))
# limit float 13.949999999999999 to two decimal points
'{0:.2f}'.format(13.95)
# sort list of strings in list `the_list` by integer suffix
sorted(the_list, key=lambda k: int(k.split('_')[1]))
# sort list of strings `the_list` by integer suffix before "_"
sorted(the_list, key=lambda x: int(x.split('_')[1]))
# pass a list of parameters `((1, 2, 3),) to sql queue 'SELECT * FROM table WHERE column IN %s;'
cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))
# find indexes of all occurrences of a substring `tt` in a string `ttt`
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
# find all occurrences of a substring in a string
[m.start() for m in re.finditer('test', 'test test test test')]
# join Numpy array `b` with Numpy array 'a' along axis 0
b = np.concatenate((a, a), axis=0)
# select multiple ranges of columns 1-10, 15, 17, and 50-100 in pandas dataframe `df`
df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]
# fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4
dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)
# fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4
dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)
# concatenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string
"""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
# check if string `the_string` contains any upper or lower-case ASCII letters
re.search('[a-zA-Z]', the_string)
# get alpha value `alpha` of a png image `img`
alpha = img.split()[-1]
# save a numpy array `image_array` as an image 'outfile.jpg'
scipy.misc.imsave('outfile.jpg', image_array)
# delete the last column of numpy array `a` and assign resulting array to `b`
b = np.delete(a, -1, 1)
# Convert float 24322.34 to comma-separated string
"""{0:,.2f}""".format(24322.34)
# Setting stacksize in a python script
os.system('ulimit -s unlimited; some_executable')
# assign values to two variables, `var1` and `var2` from user input response to `'Enter two numbers here: ` split on whitespace
var1, var2 = input('Enter two numbers here: ').split()
# fill missing value in one column 'Cat1' with the value of another column 'Cat2'
df['Cat1'].fillna(df['Cat2'])
# request URI '<MY_URI>' and pass authorization token 'TOK:<MY_TOKEN>' to the header
r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})
# check if list `li` is empty
if (len(li) == 0):
    pass
# Extract values not equal to 0 from numpy array `a`
a[a != 0]
# print a string `s` by splitting with comma `,`
print(s.split(','))
# Create list  by splitting string `mystring` using "," as delimiter
mystring.split(',')
# remove periods inbetween capital letters that aren't immediately preceeded by word character(s) in a string `s` using regular expressions
re.sub('(?<!\\w)([A-Z])\\.', '\\1', s)
# Construct an array with data type float32 `a` from data in binary file 'filename'
a = numpy.fromfile('filename', dtype=numpy.float32)
# How to get the length of words in a sentence?
[len(x) for x in s.split()]
# get a string `randomkey123xyz987` between two substrings in a string `api('randomkey123xyz987', 'key', 'text')` using regex
re.findall("api\\('(.*?)'", "api('randomkey123xyz987', 'key', 'text')")
# create a list of aggregation of each element from list `l2` to all elements of list `l1`
[(x + y) for x in l2 for y in l1]
# get date from dataframe `df` column 'dates' to column 'just_date'
df['just_date'] = df['dates'].dt.date
# sort a list `your_list` of class objects by their values for the attribute `anniversary_score`
your_list.sort(key=operator.attrgetter('anniversary_score'))
# sort list `your_list` by the `anniversary_score` attribute of each object
your_list.sort(key=lambda x: x.anniversary_score)
# split string 'a b.c' on space " " and dot character "."
re.split('[ .]', 'a b.c')
# count number of rows in a group `key_columns` in pandas groupby object `df`
df.groupby(key_columns).size()
# Print +1 using format '{0:+d}'
print('{0:+d}'.format(score))
# delete every non `utf-8` characters from a string `line`
line = line.decode('utf-8', 'ignore').encode('utf-8')
# lowercase a python dataframe string in column 'x' if it has missing values in dataframe `df`
df['x'].str.lower()
# swap values in a tuple/list inside a list `mylist`
map(lambda t: (t[1], t[0]), mylist)
# Swap values in a tuple/list in list `mylist`
[(t[1], t[0]) for t in mylist]
# Set index equal to field 'TRX_DATE' in dataframe `df`
df = df.set_index(['TRX_DATE'])
# change figure size to 3 by 4 in matplotlib
plt.figure(figsize=(3, 4))
# add column `d` to index of dataframe `df`
df.set_index(['d'], append=True)
# create a regular expression that matches the pattern '^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)' over multiple lines of text
re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)
# regular expression "^(.+)\\n((?:\\n.+)+)" matching a multiline block of text
re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)
# get equivalent week number from a date `2010/6/16` using  isocalendar
datetime.date(2010, 6, 16).isocalendar()[1]
# format floating point number  `TotalAmount` to be rounded off to two decimal places and have a comma thousands' seperator
print('Total cost is: ${:,.2f}'.format(TotalAmount))
# split string 'abcdefg' into a list of characters
re.findall('\\w', 'abcdefg')
# set columns `['race_date', 'track_code', 'race_number']` as indexes in dataframe `rdata`
rdata.set_index(['race_date', 'track_code', 'race_number'])
# replace a string `Abc` in case sensitive way using maketrans
"""Abc""".translate(maketrans('abcABC', 'defDEF'))
# get a list of values with key 'key' from a list of dictionaries `l`
[d['key'] for d in l if 'key' in d]
# get a list of values for key 'key' from a list of dictionaries `l`
[d['key'] for d in l]
# get a list of values for key "key" from a list of dictionaries in `l`
[d['key'] for d in l]
# change the font size on plot `matplotlib` to 22
matplotlib.rcParams.update({'font.size': 22})
# replace comma in string `s` with empty string ''
s = s.replace(',', '')
# get the count of each unique value in column `Country` of dataframe `df` and store in column `Sum of Accidents`
df.Country.value_counts().reset_index(name='Sum of Accidents')
# sort dictionary `d` by key
od = collections.OrderedDict(sorted(d.items()))
# sort a dictionary `d` by key
OrderedDict(sorted(list(d.items()), key=(lambda t: t[0])))
# get dictionary with max value of key 'size' in list of dicts `ld`
max(ld, key=lambda d: d['size'])
# create a dictionary containing each string in list `my_list` split by '=' as a key/value pairs
print(dict([s.split('=') for s in my_list]))
# remove all values within one list `[2, 3, 7]` from another list `a`
[x for x in a if x not in [2, 3, 7]]
# remove all duplicates from a list of sets `L`
list(set(frozenset(item) for item in L))
# remove duplicates from a list of sets 'L'
[set(item) for item in set(frozenset(item) for item in L)]
# Concatenate elements of a list 'x' of multiple integers to a single integer
sum(d * 10 ** i for i, d in enumerate(x[::-1]))
# convert a list of integers into a single integer
r = int(''.join(map(str, x)))
# create dict of squared int values in range of 100
{(x ** 2) for x in range(100)}
# get complete path of a module named `os`
imp.find_module('os')[1]
# get current CPU and RAM usage
psutil.cpu_percent()
psutil.virtual_memory()
# get current RAM usage of current program
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = (py.memory_info()[0] / (2.0 ** 30))
# print cpu and memory usage
print((psutil.cpu_percent()))
print((psutil.virtual_memory()))
# given list `to_reverse`, reverse the all sublists and the list itself
[sublist[::-1] for sublist in to_reverse[::-1]]
# extract table data from table `rows` using beautifulsoup
[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]
# find element `a` that contains string "TEXT A" in file `root`
e = root.xpath('.//a[contains(text(),"TEXT A")]')
# Find the`a` tag in html `root` which starts with the text `TEXT A`  and assign it to `e`
e = root.xpath('.//a[starts-with(text(),"TEXT A")]')
# find the element that holds string 'TEXT A' in file `root`
e = root.xpath('.//a[text()="TEXT A"]')
# round number 32.268907563 up to 3 decimal points
round(32.268907563, 3)
# round number `value` up to `significantDigit` decimal places
round(value, significantDigit)
# round number 1.0005 up to 3 decimal places
round(1.0005, 3)
# round number 2.0005 up to 3 decimal places
round(2.0005, 3)