number=5 text='test' 'Number is {0}、text is {1}'.format(number, text)
Search a substring
s = "This be a string" if s.find("is") == -1: print"No 'is' here!"
if"is"in s: print"No 'is' here!"
Replace substring
This method returns a copy of the string with all occurrences of substring old replaced by new.
str = "this is string example....wow!!! this is really string" print str.replace("is", "was") #=> thwas was string example....wow!!! thwas was really string print str.replace("is", "was", 3) #=> thwas was string example....wow!!! thwas is really string
Trim whitespace
' Hello '.strip() #=> 'Hello' ' Hello'.strip() #=> 'Hello' 'Bob has a cat'.strip() #=> 'Bob has a cat'
Embedding variable in Python 3.6 or later
a = 'sample' print(f'{a}') #=> 'sample'
🐯 List/Array
List comprehension
A list comprehension consists of the following parts:
An Input Sequence.
A Variable representing members of the input sequence.
An Optional Predicate expression.
[i for i in range(10)] #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [i for i in range(10) if i%2==0] #=> [0, 2, 4, 6, 8] [ i if i%2==0else str(i) for i in range(10)] #=> [0, '1', 2, '3', 4, '5', 6, '7', 8, '9']
r'...' is literal for Regex. It is better to use it for Regex.
import re
m = re.search(r'(?<=-)\w+'< span>, 'spam-egg')=-)\w+'<> m.group(0) #=> 'egg'
p = re.compile('name (.*) is valid') s = """ someline abc someother line name my_user_name is valid some more lines""" p.findall(s) #=> ['my_user_name']
string.replace with regular expression
import re
line = re.sub( r"(?i)^.*interfaceOpDataFile.*$", "interfaceOpDataFile %s" % fileIn, line )
Remove specific pattern from text
This is example for removing HTML tags/formatting from a string:
import re defstrip_html_tag(data): p = re.compile(r'<.*?>') return p.sub('', data)
end = 0 whileTrue: idx = WHITESPACE.match(s[end:]).end() i = end + idx if i >= size: break ob, end = decoder.raw_decode(s, i) yield ob
Generate CSV file
Generate CSV file from list(array):
import csv
items = [ ['John', 28], ['Sara', 22] ]
with open('/app/job_items.csv', 'w', encoding='utf8') as f: wr = csv.writer(f, quoting=csv.QUOTE_ALL, lineterminator='\n') wr.writerow(['name', 'age']) for i in items: wr.writerow(i)
# Write string data as CSV # csvwriter.writerow([i])
VULTR provides high performance cloud compute environment for you.
Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour).
In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!