How to split a string in Python

One of the everyday operations when dealing with strings is to divide a string using a given delimiter into an array of substrings.

We will explore how to break a string in Python in this post.

.split() function:

Strings are depicted as it has immutable property in Python. The a class contains a variety of string methods to manage the string.

The .split() method returns a delimiter-separated list of substrates. The following syntax is required:

a.split(xyz=None, maxsplit =-1)

The boundary can be a character or character set, not a regular expression. In this example, we divide the string a using the comma (,):

a = 'John,Harry,Ricky's.split(',')

The outcome is a string list:

['John', 'Harry', 'Ricky']

As a delimiter may also use a series of characters:

S = 'John: :Harry: :Ricky's.split(': :')

['John', 'Harry' and 'Ricky']

If Max split is defined, the number of splits will be reduced. There is no limit on the number of splits, if not stated or -1.

s = 'John; Harry; Ricky's.split(';', 1)

The maxsplit+1 element in the result list will be maximized:

['John,' 'Harry; Ricky']

If the xyz is not defined or Null, the string will be split as a delimiter using whitespace. As a single separator, all consecutive whitespaces are considered. Also, there would be no empty strings if the string includes trailing and leading whitespaces. Let’s take a look at the following example to further explain this:

' JohnHarry Ricky Anthony Carl'.split()

Output = ['John', 'Harry', 'Ricky ', 'Anthony', 'Carl']

'JohnHarry Ricky Anthony Carl'.split()

Output = [' ', 'John', ' ', 'Harry', 'Ricky', ' ', ' ', 'Anthony', 'Carl', ' ']

When no delimiter is used, no empty strings are found in the return list. The leading, trailing, and consecutive whitespace will cause the result to contain empty strings if the delimiter is set to empty space.

Conclusion

One of the most common operations is breaking strings. You should have a clear understanding of how to break strings in Python after this.

How to Install Python Pip on Ubuntu 20.04

If Python is still new to you, Python is a high-level programming language oriented towards objects that have become increasingly popular over the years. Python is commonly used in software, device management, analyzing scientific and numeric data, and much more.

It is possible to install either Python 2 or Python 3 on Ubuntu 20.04. With Ubuntu 20.04, though, Python 3 is the default version. PIP is a software tool that allows you to install different packages of Python on your device. Packages can be installed from the PyPI Python Package index repository and other index repositories into your framework with the PIP tool’s help.

It is strongly recommended to install the module’s dev package with the apt tool when installing a global Python module. They are checked to function correctly on Ubuntu systems. The prefix for Python 3 packages is python3- and the prefix for Python 2 packages is python2-.

Using Pip to globally install a module only if no deb package exists for that module.

You prefer to use pips only in a virtual world. For a particular project, Python Virtual Environments allows you to install Python modules in an isolated area rather than installed globally. This way, you do not have to worry about other Python projects being affected.

Installing Pip in Python 3

To install the Python 3 pip for Ubuntu 20.04, run the following root, or sudo user commands on your terminal:

sudo apt update sudo apt install python3-pip

All the dependencies needed to construct Python modules will also be installed with the above instruction.

Verify the installation when the installation is completed by reviewing the pip version:

pip3 --version

Install a Python 2 pip

In the repositories of Ubuntu 20.04, Pip for Python 2 is not included. We’ll be using the get-pip.py script to build a pip for Python 2.

Sudo Add-apt-Universe Repository

Update the index for the packages and install Python 2:

sudo apt update sudo apt install python2

To download a get-pip.py script, use curl:

curl https://bootstrap.pypa.io/get-pip.py --output get-pip.py

You can run the installing script as sudo user with python2 to install Pip for Python 2 once the repository is enabled:

sudo python2 get-pip.py

Pips can be installed worldwide. If it is just for your user to install, run the command without sudo. Setuptools and wheels are also installed in the script, enabling you to install source distributions.

Verify installation by the version number of the pip:

pip2 --version

How do you make use of Pip?

Let’s see, a few useful simple commands for pips. With Pip, you can install PyPI, version control, local projects, and delivery file packages. Generally, PyPI packages are installed.

To display the list of all options and pip commands, type:

pip3 --help

Using Pip <command> –help, you can get more information about a particular command. To get more information about the install order, for example, type:

pip3 install –help

Using Pip to install Packages

If you want to install a scrapy kit used to scrape data from websites and extract it.

You must run the following command to install the latest version of the package:

pip3 install scrapy

To install a particular version of the append == package, and the version number after the name of the package:

pip3 install scrapy==1.5

Download the requirements.txt packages:

Requirements.txt is a text file that includes a list of versions of the pip packages needed to run a particular Python project.

To install a list of requirements listed in a file, use the following command:

pip3 install -r requirements.txt

Installed Packages listing

Use the following command to list all the installed pip packages:

pip3 list

Upgrade with Pip a Kit

To update the kit that is already installed to the new version, enter:

pip3 install --upgrade package_name

Uninstalling Pip Packages

To uninstall a running package:

pip3 uninstall package_name

Completion

Here you have learned about installing pip on your Ubuntu operating system and using pips to handle Python packages.

How to Find the Length of a List in Python

Lists are one of the most commonly used data types in Python and store collections of the same kind.

In this article, we will see how to find the length of a list.

len() Function

If you want to find the length of the given object, then in Python, there is a built-in function len(), giving you the length of the given object (object means a list, tuple, string, dictionary, etc.)

The syntax of the len() function is as follows:

len(list)

The function allows only one argument. The declared value is an integer that is the number of elements in the list.

Here is an example:

capitals = ['Tokyo', 'Sofia', 'India', 'Budapest', 'America']

list_len = len(capitals)

print("The list has {0} elements.".format(list_len))
Output:

The list has 5 elements.

Using Loop

The another way to find the length of a list is to use them for a loop. This works by fixing up a counter and looping through all the elements of the list. On each repetition, the current value of the counter variable is incremented by one.

With the help of the following code, the snippet will get an idea of finding the length of an object using the loop.

capitals = ['Japan', 'America', 'India', 'Budapest', 'Italy']

counter = 0

for capital in capitals:

  counter = counter + 1

print("The list has {0} elements.".format(counter))
output:

The list has 5 elements.

As we cannot trust this method, it favors using the len() function in Python.

Conclusion

In this article, we have seen finding the length of a list in Python list and using the len() function only. If you have any queries related to this len(), then feel free to connect us.

How to Convert String into Integer in Python

Objects can be any kind of data type in Python, i.e. integer and string. Sometimes, you will need to convert one data form to another while writing Python code. For example, it needs to be transformed into an integer to perform a math operation on a number represented as a string. Here’s how to convert a string in Python to an integer.

int() function in Python

The built-in function int() returns an integer decimal object from a given number or String. It takes the form below:
int(a, base=10)

Two arguments are accepted by the function:

  • a – The number or String to be transformed to an integer.
  • base – Reflects the first argument’s numeral scheme. It can have a value between 0 and 2–36. It is optional to render this statement. The default base is always 10 if no base is defined (decimal integer). Integers are usually expressed in hexadecimal format i.e., base 16, decimal has base 10, octal has base 8, and binary has base 2.

If the given string cannot be interpreted as an integer, the ValueError exception is executed by the function.

Converting a String to Integer in Python

A ‘string’ is a list of characters declared in Python using a single (‘), double (“), or triple quotes (“””). If you use quotes to declare a variable that contains only numbers, its data type is set to String. Consider the instance below:

no_of_day = "23"
type(no_of_day)

The type() function tells us that the String object is the no_of_day variable.

<type 'str' > type

Let’s try on the variable to do a math operation:

print(day+5)

After that, Python throws an exception, i.e., TypeError, because it is unable to perform a string and integer addition calculation:

Traceback (last call last):
'' file, line 1, in
TypeError: can't concatenate items with 'str' and 'int.'

To convert a string representation of a decimal integer to an int, transfer a string that returns a decimal integer: to the int() function.

no_of_day = "23" days
no_of_day_int = int(no_of_day)
type(no_of_day_int)
<type 'int' >

The total operation will be done successfully if you try to do the math now:

print(no_of_day_int+5)
28

Remember, the commas you need to delete before passing the number to the int() function if the number contains commas, marking off thousands, millions, etc.:

total = "1,000,000"int(total.replace(",", ""))
1000000

When you execute the conversion between string to an integer, just make sure that you are using a correct base representing integers in various number systems. The number 54731 is expressed as D5CE in the hexadecimal method, for instance. You need to use Base 16 to convert it to a decimal integer:
If you move the D5CE String without setting the base to the int() function, the ValueError exception will be:

int ("D5CE", 16)
54731
Traceback (last call last):
'' file, line 1, in
ValueError: invalid literal with base 10 for int(): 'D5CF'

Conclusion:
In Python, using the int() function, you can convert a string to an integer.

How to Check Python Version

Python is one of the most successful programming languages in the world. It is used to develop websites, write scripts, machine learning, analyze data, and many more.

This article explains how to check what Python version is installed on your operating system working the command line. This can be beneficial when installing applications that require a particular version of python.

We will also explain to you how to programmatically determine what Python version is installed on the system where the Python script is running. For example, when writing Python scripts, you will require determining whether the script supports python’s version on the user’s machine.

Python Versioning

Python uses semantic versioning. Production-ready releases are versioned in the following scheme:

MAJOR.MINOR.MICRO

For example, in Python 3.6.8, 3 is a major version, 6 is a minor version, and 8 is a micro version.

  •  MAJOR – a python, has two major versions that are not fully cooperative: Python 2 and Python 3. For example, 3.5.7, 3.7.2, and 3.8.0 are all part of the Python 3 major version.
  • Minor: These announcements are bringing new features and roles. For example, 3.6.6, 3.6.7, and 3.6.8 are all part of the Python 3.6 minor version.
  • Micro: The new micro versions include various bug fixes and enhancements.

Development announcements have additional qualifiers. For more information, read the Python “Development Cycle” documentation.

Checking Python Version

Python is pre-installed on most maximum Linux distributions and macOS. On Windows, you have to download and install it if you want.

To get which version of python is fixed on your system, run the Python –version or Python -V command:

$ python --version

The order will print the default Python version, in this case, that is 2.5.15. The version installed on your system maybe another.

Output:

Python 2.7.15+

The default version of python will be applied by all scripts that have /usr/bin/python set as an interpreter in the script’s shebang line.

Some Linux distributions have various versions of python installed at the same time. The Python 3 binary is frequently named python3, and the Python 2 binary is called python or python2, but that may not always be the case.

You can check if you have Python 3 installed by typing:

$ python3 --version
Output:

Python 3.6.8

Python 2 support ended in 2020. Python 3 is the today and future of the programming language.

At the time of writing this article, the newest major release of python is version 3.8.x. The possibilities are that you can own an older version of Python 3 installed on your system.

If you want to install the most advanced python version, the method depends on your running system.

Programmatically Checking Python Version

Python 2 and Python 3 are different. The code written in Python 2.x may not work in Python 3.x, so you have to write two other codes.

The sys module that is open in all Python versions gives system-specific parameters and functions. sys.version_info enables you to discover the Python version installed on the system. It reflects a tuple that contains the five version numbers: major, minor, micro, release level, and serial.

Let’ say you have a script that needs at least Python version 3.5, and you want to tell whether the system meets requirements. You can do that by merely monitoring the major and minor versions:

import sys

if not (sys.version_info.major == 3 and sys.version_info.minor >= 5):

   print("This script requires Python 3.5 or higher!")

   print("You are using Python {}.{}.".format(sys.version_info.major, sys.version_info.minor))

   sys.exit(1)

If you run the script using Python version less than 3.5, it will produce the following output:

Output:

Python 3.5 or higher is required to run this script. 

You are using Python 2.5.

To write Python code that runs below both Python 3 and 2, use the future module. It enables you to run Python 3.x-compatible code below Python 2.

Conclusion: 

Using the python --version, it is very easy to find what version of python is installed on your system.