-2

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.

  • How are you reading this? If you read it using the `csv` module, then you'll just use the first column. You can always do `col1 = line.split(',')[0]`, or even `col1 = line.partition(',')[0]`. – Tim Roberts Jul 27 '22 at 19:10
  • 1
    why do talk about "multiple delimiter" ? Just split on comma – azro Jul 27 '22 at 19:11
  • I am using from txt – Ratna Raju Jul 27 '22 at 19:12
  • Does this answer your question? [Split a string by a delimiter in python](https://stackoverflow.com/questions/3475251/split-a-string-by-a-delimiter-in-python) – mkrieger1 Jul 27 '22 at 19:14

2 Answers2

0

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]
Guillaume
  • 449
  • 3
  • 14
0

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.

NLindros
  • 1,683
  • 15
  • 15