How do I lowercase a string in Python?
Use str.lower(): “Kilometer”.lower()
Use str.lower(): “Kilometer”.lower()
>>> x = “Hello World!” >>> x[2:] ‘llo World!’ >>> x[:2] ‘He’ >>> x[:-2] ‘Hello Worl’ >>> x[-2:] ‘d!’ >>> x[2:-2] ‘llo Worl’ Python calls this concept “slicing” and it works on more than just strings. Take a look here for a comprehensive introduction.
The sorted() function takes a key= parameter newlist = sorted(list_to_be_sorted, key=lambda d: d[‘name’]) Alternatively, you can use operator.itemgetter instead of defining the function yourself from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’)) For completeness, add reverse=True to sort in descending order newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’), reverse=True)
There isn’t a built-in flag yet, but you can use: pip list –outdated –format=freeze | grep -v ‘^\-e’ | cut -d = -f 1 | xargs -n1 pip install -U For older versions of pip: pip freeze –local | grep -v ‘^\-e’ | cut -d = -f 1 | xargs -n1 pip install -U The … Read more
some_list[-1] is the shortest and most Pythonic. In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element. You can also set list elements … Read more
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop(): my_dict.pop(‘key’, None) This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop(‘key’)) and key does not exist, a KeyError is raised. To delete a key … Read more
>>> a = “545.2222” >>> float(a) 545.22220000000004 >>> int(float(a)) 545
RENAME SPECIFIC COLUMNS Use the df.rename() function and refer the columns to be renamed. Not all the columns have to be renamed: df = df.rename(columns={‘oldName1’: ‘newName1’, ‘oldName2’: ‘newName2’}) # Or rename the existing DataFrame (rather than creating a copy) df.rename(columns={‘oldName1’: ‘newName1’, ‘oldName2’: ‘newName2’}, inplace=True) Minimal Code Example df = pd.DataFrame(‘x’, index=range(3), columns=list(‘abcde’)) df a b … Read more
in tests for the existence of a key in a dict: d = {“key1”: 10, “key2”: 23} if “key1” in d: print(“this will execute”) if “nonexistent key” in d: print(“this will not”) Use dict.get() to provide a default value when the key does not exist: d = {} for i in range(10): d[i] = d.get(i, … Read more
To get the full path to the directory a Python file is contained in, write this in that file: import os dir_path = os.path.dirname(os.path.realpath(__file__)) (Note that the incantation above won’t work if you’ve already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working … Read more