Category Python

How to round a number in Python

round()

The round() function rounds a given number with the specified number of decimals. If you don’t specify the number of decimals, the default will be zero decimals. print(round(32.8476)) print(round(32.8476,1)) print(round(32.8476,2)) print(round(32.8476,3)) 33 32.8 32.85 32.848

How to reverse a string in Python

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

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

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…