Python Lessons – 5.8 Some useful functions for numbers and strings

Python Lessons - 5.8 Some useful functions for numbers and strings

Some useful functions for strings

Python already contains some very useful functions and methods to perform some string operations.

  • join() – concatenates a list of strings with a separator character
  • replace() – replaces one substring with another
  • startswith() – checks if the string starts with a particular sequence of characters
  • endswith() – check if the string ends with a particular sequence of characters
  • upper() – converts all string characters to uppercase
  • lower() – converts all string characters to lowercase
  • split() – splits a string into a list of strings at a separator character

Let’s see some examples

if you run it, you get:

As you can see they are all methods of the string object.

Some useful functions with numbers

As with strings, the basic Python distribution already has a number of useful features when working with numbers. Let’s see some together

  • min () – this function returns the minimum value within a sequence or a list of numbers
  • max () – this function returns the maximum value within a sequence or a list of numbers
  • abs () – calculates the absolute value of a number
  • round () – this function rounds the number for a certain number of decimal places
  • sum () – calculate the sum of a list of numbers

Let’s see some examples together

if you run it, you get

The all(), any() and enumerate() functions

Python provides some very useful functions regarding lists.

The functions all () and any () are very useful when you want to make all the elements of a list available. In the case of all() it will return True only if all the elements satisfy this condition, in the case of any() it is sufficient that at least one satisfies it.

if you run it, you get

The enumerate() function is used to perform an iteration for all the elements of a list, having both indices and values as variables to be managed.

if you run it, you get

⇐ Go to Python Lesson 5.7 – String Formatting 

Go to Python Lesson 6.1 – Functional Programming ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.