06 Sep 2022
identify if all caps
if all(char.isupper() for char in first):
eg:
if all(char.isupper() for char in first):
new_first = string.capwords(first, sep=None)
print(f"{first} ----> {new_first}")
prints:
AMELIE ----> Amelie
JAN ----> Jan
ERIC ----> Eric
capitalise strings
import string
first = 'pierre-GARCIA'
if not first[0].isupper():
first = first.strip()
if '-' in first:
new_first = string.capwords(first, sep='-')
else:
new_first = string.capwords(first, sep=None)
print(f"{first} ----> {new_first}")
# Can be used with separator, ie
# formatted = string.capwords(sentence, sep = 'g')
prints:
pierre-GARCIA ----> Pierre-Garcia
print list with index
highlights = ['x', 'y', 'z']
for index, value in enumerate(highlights):
print(index, value)
prints:
0 x
1 y
2 z
for count instead of index:
for index, value in enumerate(highlights):
print(index + 1, value)
print exception error
try:
# write code that may throw exception
except Exception as e:
# the code for handling the exception
print(e)
09 Sep 2022
printing to file
easiest method
with open('filename.txt', 'w') as f:
print('This message will be written to a file.', file=f)
or to append continuously replace w
with a
:
with open('filename.txt', 'a') as f:
print('This message will be written to a file.', file=f)
redirecting a Python's script output in the terminal
If script run from Terminal, redirect the output (print) of the script to a file, using a single right angle bracket:
$ python3 hello.py > output.txt
redirecting the Standard Output Stream
to print to file:
original_stdout = sys.stdout # save original stdout
with open('test.txt', 'w') as f:
sys.stdout = f
print("TEST")
sys.stdout = original_stdout # reverts to original stdout
CSV to database with Pandas
Did you know you can save a #pandas 🐼 DataFrame into a database?
— Mike Driscoll (@driscollis) August 29, 2022
All you need is a valid database connection and then you can use the `to_sql()` method.
Here's an example using #SQLite and #Python 🐍🔥 pic.twitter.com/S8vmFTyNKh
check if directory exists
Use os.path.isdir for directories only:
os.path.isdir('new_folder')
Use os.path.exists for both files and directories:
os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
play the system sound bell
print('\a')
identify if a string is a number
.isdigit()
string = "12345"
if string.isdigit():
print("The string contains only digits.")
else:
print("The string does not contain only digits.")
or .isnumeric()
string = "12345"
if string.isnumeric():
print("The string contains only digits.")
else:
print("The string does not contain only digits.")