2

Ok, so basically I have a CSV file with a list of phones and their IMEI numbers which consists of a 15 digit number - currently formatted like so "000000000000000" and I need take that list from the csv and generate ouput IMEI format to "00 000000 000000 0" A space after the first 2 digits, one space after the next six, and finally a space before the last, but I am not sure how to go about it :(

import csv

file_csv = input("enter file name: \n")
phone_imei=[]

with open(file_csv, "r") as f:
reader = csv.reader(f, delimiter = ',')
for row in reader:
    phone_imei.append(row[3])  # list of IMEI in this row#
location_file.close()

print(phone_imei)
jpp
  • 159,742
  • 34
  • 281
  • 339
Vvega
  • 37
  • 6

1 Answers1

1

My starting assumption is you are able to get a list of strings from your csv file into list phone_imei.

For the string format you desire, you need to use string slicing / indexing. Conveniently, this is the same as for lists, so see Understanding Python's slice notation.

Here is one example:

x = "123456789123456"
res = x[:2] + ' ' + x[2:8] + ' ' + x[8:14] + ' ' + x[14]

'12 345678 912345 6'

You can incorporate this logic in a couple of ways.

As you go along...

def string_formatter(x):
    """Format telephone number with spaces."""
    return x[:2] + ' ' + x[2:8] + ' ' + x[8:14] + ' ' + x[14]

for row in reader:
    phone_imei.append(string_formatter(row[3]))

At the end...

phone_imei = list(map(string_formatter, phone_imei))
# equivalently, phone_imei = [string_formatter(i) for i in phone_imei]
jpp
  • 159,742
  • 34
  • 281
  • 339