# Python bulding Strings # https://stackoverflow.com/questions/19926089/python-equivalent-of-java-stringbuffer # Append strings to a list variable and use string join myList.append(“string value”) ‘’.join(myList) ‘,’.join(myList) # Python ternary operator # https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator # The true value then the test and then the false # <true value> if <test> else <false value> x = 1 if a > b else -1 # Swapping values # https://www.programiz.com/python-programming/examples/swap-variables # Assignment can hadle multiple values x,y = y,x # Testing if a property is defined # https://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python # https://www.safaribooksonline.com/library/view/python-cookbook/0596001673/ch17s02.html # Example 1 try: x except NameError: x = None if x is None: some_fallback_operation( ) else: some_operation(x) # Example 2 try: do_something(obj.property_name) except AttributeError: do_something_else() # Mocking classes when import not available try: import Module as mod o = mod.SomeClass except: class mod(object): @staticmethod() class SomeClass(): pass # Copy a file with all attributes # https://stackoverflow.com/questions/17685217/keeping-file-attributes-on-a-copy # https://stackoverflow.com/questions/11348953/how-can-i-set-the-last-modified-time-of-a-file-from-python from shutil import copy2 copy2(src, dest) # or shutil.copy(src, dest) shutil.copystat() # execute right after shutil.copy() # Is a string a number # https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float def is_number(s): try: float(s) return True except ValueError: return False # Sort a dictionary of tuples or sub-dictionary items # https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value # https://docs.python.org/2/library/operator.html#operator.itemgetter # where 1 is the position in the sub-dict or tuple to use in sorting # sorted() will return a sorted list of the items sorted_values = sorted(some_dict.items(), key=operator.itemgetter(1)) # Join to lists # https://stackoverflow.com/questions/1720421/how-to-concatenate-two-lists-in-python listone = [1,2,3] listtwo = [4,5,6] mergedlist = listone + listtwo # Give class ability to get property using dictionary syntax # https://stackoverflow.com/questions/31807172/myclass-object-has-no-attribute-getitem # Implement the __getitem__ method. class MyClass(object): self.some_data = 1 def __getitem__(self, item): return getattr(self, item) o = MyClass() print(o["some_data"]) # Reload module dynamically # https://stackoverflow.com/questions/5516783/how-to-reload-python-module-imported-using-from-module-import # https://stackoverflow.com/questions/4670586/how-to-reload-the-code-of-a-method-of-class-object-in-python # https://stackoverflow.com/questions/29960634/reload-the-currently-running-python-script # https://itom.bitbucket.io/v3-0-0/docs/08_scriptLanguage/pymod-reload-modules.html # https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module # https://docs.python.org/2/library/functions.html#reload # Must import module as a single name import my_library.my_module as mod reload(mod) from mod import A # Get file information (creation time, mod time, etc) # https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python import os, time (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file) print("last modified: %s" % time.ctime(mtime)) # Reading Writing to files # https://stackoverflow.com/questions/35611797/how-do-i-use-writelines-correctly # https://stackoverflow.com/questions/1223289/how-to-write-native-newline-character-to-a-file-descriptor-in-python # ** http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python # ** http://www.pythonforbeginners.com/cheatsheet/python-file-handling # Write - Using "with" syntax ensure proper closing of file. with open(file_path, "w") as f f.writelines([1,2,3,4,5]) # writes one line for each list value f.write(2) # write a value to the file f.write("\n") # add new line to file # Read - Using "with" syntax ensure proper closing of file. with open(file_path) as f line = f.readline() for line in f do_something(line) # Python strings # https://www.shortcutfoo.com/app/dojos/python-strings/cheatsheet # https://www.dotnetperls.com/substring-python # Example 1 string = "abcdefgh" # Three characters starting at index 2. offset = 2 length = 3 sliced = string[offset:offset+length] print(sliced) # Access/Process environment variables # https://stackoverflow.com/questions/4906977/how-do-i-access-environment-variables-from-python/9926915 import os x = os.environ["PATH"] x = os.path.expandvars("JAVA_HOME") # Add property to class dynamically # https://stackoverflow.com/questions/1325673/how-to-add-property-to-a-class-dynamically class Foo(object): pass foo = Foo() foo.a = 3 Foo.b = property(lambda self: self.a + 1) foo.b # User property decorators # https://stackoverflow.com/questions/1684828/how-to-set-attributes-using-property-decorators # https://docs.python.org/3/library/functions.html#property class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value # Adding modules to the python path at runtime # https://stackoverflow.com/questions/4383571/importing-files-from-different-folder # some_file.py import sys # add at begining of path list - higher priority sys.path.insert(0, '/path/to/application/app/folder') # contains module file.py # add to end of path list - lower priority sys.path.append('/path/to/application/app/folder') # contains module file.py import file # import "/path/to/application/app/folder/file.py" # Calling base class __init__ in child class __init__ # https://stackoverflow.com/questions/19205916/how-to-call-base-classs-init-method-from-the-child-class # Example class BaseClass(object): def __init__(self, *args, **kwargs): pass class ChildClass(BaseClass): def __init__(self, *args, **kwargs): super(ChildClass, self).__init__(*args, **kwargs) # Exmaple class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg class ElectricCar(Car): def __init__(self, battery_type, model, color, mpg): self.battery_type=battery_type super(ElectricCar, self).__init__(model, color, mpg) # Current script being executed script_path = os.path.abspath(__file__) dirname, filename = os.path.split(os.path.abspath(__file__)) # Resolve relative path print("Relative path: ", os.path.abspath("..\\..\\bin"))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question