0

So I have a file where a bunch of coordinates are in. But one x has its y value in the same line just seperated by a space. How do I split each line into two seperated pieces up so that I get the y and the x coord seperate(eg in a strig array)? Coordinate example:

934 100
jonas
  • 164
  • 1
  • 11

5 Answers5

0

Use split method to split the line default delimeter is space

with open("file") as f:
    for line in f.readlines():
        line=line.strip().split()
        x=line[0]
        y=line[1]
Roushan
  • 4,074
  • 3
  • 21
  • 38
0

Write as you say it - split the line on whitespace:

line = "934 100"
x, y = line.split()
Austin
  • 25,759
  • 4
  • 25
  • 48
0

Simply use line.split() for each string line.

It also works on lines with more than two coordinates.

Examples:

  • line = "934 100", x, y = line.split(), print(x,y) = 934 100

  • line = "1 61 298 3333 ", a, b, c, d = line.split(), print(a,b,c,d) = 1 61 298 3333

0
with open(filename, "r") as fd:
lines_list = fd.readlines()
for index in range(len(lines_list)):
    x, y = lines_list[index].split(' ')
    print(x, y)

open file in read mode i.e "r"

with open(filename, "r") as fd:

Using readlines() we will get all the data of file in form of list of lines

lines_list = fd.readlines()

For each line split the line using space as delimiter and assign to x and y variables

x, y = lines_list[index].split(' ')
0

Use split() List compression way of doing this is:

//suppose your input is 10 22
c=[int(temp) for i in input().split()]

//it will give us a list with elements [10, 22]
print(c) //[10, 22]

If you are reading from the file:

with open(file_path , "r") as file:
 lines_list = file.readlines()
 for index in range(len(lines_list)):
 x, y = lines_list[index].split(' ')
 print(x, y)

If you have it as a string:

s = “10 22”
x, y=s.split()
print(x, y) //10 22
Raman Mishra
  • 2,635
  • 2
  • 15
  • 32