Python Tip #76 (of 365):

Don't call the string split() method with a space character

Instead of this:

words = some_string.split(" ")

Do this:

words = some_string.split()

Calling the split method without arguments will:

โ€ข Trim whitespace from either end of the string
โ€ข Split by any amount of consecutive whitespace characters

Note that "whitespace characters" isn't just spaces: newlines and tabs count also.

More on the split() method: https://pym.dev/string-split-method/

#Python #DailyPythonTip

The string split method in Python

Strings can be split by a substring separator. Usually the string split is called without any arguments, which splits on any whitespace.

Python Tip #75 (of 365):

Don't use the string split() method for splitting lines. Use the splitlines() method instead.

Instead of calling split with "\n":
lines = poem.split("\n")

Use the splitlines method:
lines = poem.splitlines()

The string splitlines method will:

โ€ข Trim a trailing newline (if there is one)
โ€ข Split by "\r\n", "\n", or "\r"

More on splitlines: https://pym.dev/splitlines/

This week's daily tips are all about string methods in Python.

#Python #DailyPythonTip

Why splitlines() instead of split("\n")?

To split text into lines in Python, use the splitlines() method, not the split() method.

Python Tip #74 (of 365):

Print blank lines with print()

Instead of this:

print("TITLE\n")
print("Descrption")

Consider this:

print("TITLE")
print()
print("Descrption")

It's a bit easier to see that there's meant to be a blank line when a separate print call is used instead of just putting "\n" at the end of a string.

#Python #DailyPythonTip

Python Tip #73 (of 365):

Use self-concatenation to make horizontal rules

To print 80 '=', '-', or '*' characters, you can multiply a single-character string by the number 80:

>>> print("-" * 80)
--------------------------------------------------------------------------------

#Python #DailyPythonTip

Python Tip #72 (of 365):

You can redirect all printed output in Python with contextlib.redirect_stdout

from contextlib import redirect_stdout
import io
with redirect_stdout(io.StringIO()) as output:
print("hello")
printed_text = output.getvalue()

The redirect_stdout context manager temporarily sets Python's standard output file-like object (sys.stdout) to a different file object. It's most commonly used with an in-memory fake file object (the io.StringIO class).

#Python #DailyPythonTip

Python Tip #71 (of 365):

Print non-standard output to standard error

Python's print function writes to the "standard output" stream by default.

But terminals have a second output stream that also writes to the screen: standard error.

Standard error is most often used for:

- error messages
- diagnostic output
- output that shouldn't be mixed in with the rest of the program's output

๐Ÿงต (1/2)

#Python #DailyPythonTip

Python Tip #70 (of 365):

Print partial lines by specifying end="" ๐Ÿงต

Instead of writing to "sys.stdout" to avoid printing newlines:

sys.stdout.write(prefix)
sys.stdout.write(remainder + "\n")

Consider passing end to print():

print(prefix, end="")
print(remainder)

#Python #DailyPythonTip

Python Tip #69 (of 365):

Joining and then printing? Consider using print() to do your joining instead.

Instead of passing an iterable to the string join method first:
print(", ".join(names))

You could unpack the iterable into a print call and specify a sep:
print(*names, sep=", ")

You can also often remove string conversions (print converts the given values to strings).

So this:
print(", ".join(str(n) for n in numbers))

Can become this:
print(*numbers, sep=", ")

#Python #DailyPythonTip

Python Tip #68 (of 365):

Instead of printing an f-string with a single space between values, consider passing 2 arguments to print

Instead of this:

print(f"User: {name}")

You could do this:

print("User:", name)

Why?

Less syntax. That's all.

#Python #DailyPythonTip

Python Tip #67 (of 365):

When making a class that should support inheritance, don't hard-code references to your own class. Use type(self) to dynamically look up the current class.

This is particularly relevant in __repr__.

Instead of this:

def __repr__(self):
return f"MyClass(...)"

Do this:

def __repr__(self):
class_name = type(self).__name__
return f"{class_name}(...)"

This ensures instances of child classes show the right type in their repr()/str().

#Python #DailyPythonTip