How to reverse a string in Python

To reverse a string use the slice syntax: my_string = "ferrari" my_string_reversed = my_string[::-1] print(my_string) print(my_string_reversed) ferrari irarref The slice syntax allows you to set a step, which is -1 in the example. The default step is 1, that is,…

How to get the current date and time in Python

If you want just the current date, simply use the today() method from the date imported from the datetime module. from datetime import date current_date = date.today() print(current_date) 2020-05-02 If you want the current date and also the time, use…

How to reverse a list in Python

To reverse a list in-place, that is, without creating a new list, use the builtin reverse() method from list: car_brands = ["bmw", "ferrari", "mclaren"] print(car_brands) car_brands.reverse() print(car_brands) ['bmw', 'ferrari', 'mclaren'] ['mclaren', 'ferrari', 'bmw'] To keep the original list and assign…

How to find the index of an item in a list in Python

Use the buit-in index() method from list to find the index of an item in a list in Python. Remember the index count starts at 0, so the position of ‘mclaren’ is 2. car_brands = ['bmw', 'ferrari', 'mclaren'] position =…

Adding days to a date in Python

The timedelta object from the datetime module allows you to add any number of days to a date object. In this example I always take the current date using the date.today() method. Then I set a timedelta of 2 days…

Converting datetime into string in Python

Let’s see how to convert a datetime into a string in Python. This conversion can be done using the strftime() method from the datetime class. This example shows a few different formats for current date and time: Default date and…

How to subtract days from a date in Python

The timedelta object from the datetime module allows you to subtract any number of days from a date object. In this example I always take the current date using the date.today() method. Then I set a timedelta of 2 days…