Skip to main content
 首页 » 编程设计

python之如何更改 IMEI 号码列表的格式以包含空格

2025年01月19日10mayingbao

好的,基本上我有一个 CSV 文件,其中包含电话列表及其 IMEI 编号,其中包含一个 15 位数字 - 当前格式如下“000000000000000”,我需要从 csv 中获取该列表并生成输出 IMEI 格式到 "00 000000 000000 0"前 2 位数字后一个空格,接下来的 6 位数字后一个空格,最后一个空格,但我不知道该怎么做 :(

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) 

请您参考如下方法:

我的初始假设是您能够从 csv 文件中获取字符串列表到 phone_imei 列表中。

对于你想要的字符串格式,你需要使用字符串切片/索引。方便的是,这与列表相同,因此请参阅 Understanding Python's slice notation。

举个例子:

x = "123456789123456" 
res = x[:2] + ' ' + x[2:8] + ' ' + x[8:14] + ' ' + x[14] 
 
'12 345678 912345 6' 

您可以通过多种方式合并此逻辑。

随着你的前进......

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])) 

最后...

phone_imei = list(map(string_formatter, phone_imei)) 
# equivalently, phone_imei = [string_formatter(i) for i in phone_imei]