How to split the input in Python

Question:

I have the input like this

8.8.8.8,678,fog,hat
8.8.4.4,5674,rat,fruit
www.google.com,1234,can,zone

I want to split this input in Python so that only the IP address needs to be fetched which I will use for PING purpose. I really appreciate your help in this regard.

Asked By: Ratna Raju

||

Answers:

Let’s say one line of your data is in a variable called line. Then you can get the ping address this way:

ping = line.split(',')[0]
Answered By: Guillaume

Guessing that your input is in a .csv file.
You could use Pandas or built in csv library to parse it. Using the latter in the example below.

import csv

with open("my_input.csv") as file:
    csv_reader = csv.reader(file, delimiter=",")
    ip_adresses = [ip for ip, *_ in csv_reader]

print(ip_adresses)

>> ['8.8.8.8', '8.8.4.4', 'www.google.com']

I collect the first item of the each row by using list unpacking.

Answered By: NLindros
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.