How do I print curly-brace characters in a string while using .format?

You need to double the {{ and }}: >>> x = ” {{ Hello }} {0} ” >>> print(x.format(42)) ‘ { Hello } 42 ‘ Here’s the relevant part of the Python documentation for format string syntax: Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is … Read more

How can I randomly select an item from a list?

Use random.choice(): import random foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] print(random.choice(foo)) For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice(): import secrets foo = [‘battery’, ‘correct’, ‘horse’, ‘staple’] print(secrets.choice(foo)) secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class: import random … Read more

How do I determine if an object has an attribute in Python?

Try hasattr(): if hasattr(a, ‘property’): a.property See zweiterlinde’s answer below, who offers good advice about asking forgiveness! A very pythonic approach! The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except … Read more

How to leave/exit/deactivate a Python virtualenv

Usually, activating a virtualenv gives you a shell function named: $ deactivate which puts things back to normal. I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports deactivate as the way to escape from all virtualenvs. If you are trying to leave an Anaconda environment, the command depends … Read more

How to print without a newline or space

In Python 3, you can use the sep= and end= parameters of the print function: To not add a newline to the end of the string: print(‘.’, end=”) To not add a space between all the function arguments you want to print: print(‘a’, ‘b’, ‘c’, sep=”) You can pass any string to either parameter, and … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)