How do I remove a substring from the end of a string?

strip doesn’t mean “remove this substring”. x.strip(y) treats y as a set of characters and strips any characters in that set from both ends of x. On Python 3.9 and newer you can use the removeprefix and removesuffix methods to remove an entire substring from either side of the string: The relevant Python Enhancement Proposal is PEP-616. On Python 3.8 and older you can use endswith and slicing: Or a regular expression:

Import error when trying to import tensorflow with gpu

If you are using TensorFlow with GPU, you need to install CUDA and cuDNN. Please follow instructions on https://www.tensorflow.org/install/ If you have already install CUDA and cuDNN, but still get this error, then you probably forgot to export your libraries: for Linux, you may need to set LD_LIBRARY_PATH to include CUDA libraries.

split python source code into multiple files?

I am researching module usage in python just now and thought I would answer the question Markus asks in the comments above (“How to import variables when they are embedded in modules?”) from two perspectives: variable/function, and class property/method. Here is how I would rewrite the main program f1.py to demonstrate variable reuse for Markus: … Read more

Why is IoC / DI not common in Python?

I don’t actually think that DI/IoC are that uncommon in Python. What is uncommon, however, are DI/IoC frameworks/containers. Think about it: what does a DI container do? It allows you to wire together independent components into a complete application … … at runtime. We have names for “wiring together” and “at runtime”: scripting dynamic So, a DI container is nothing … Read more

How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can create a list of keys for a dictionary d using keys = list(d), and then access keys in the list by index keys[i], … Read more

Best way to replace multiple characters in a string?

Replacing two characters I timed all the methods in the current answers along with one extra. With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace(‘&’, ‘\&’).replace(‘#’, ‘\#’). Timings for each function: a) 1000000 loops, best of 3: 1.47 μs per … Read more