【问题标题】:How can I change the format of an IMEI number list to include spaces?如何更改 IMEI 号码列表的格式以包含空格?
【发布时间】:2018-04-29 08:41:42
【问题描述】:

好的,所以基本上我有一个 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的例子

标签: python string python-3.x csv input


【解决方案1】:

我的开始假设是您能够从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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多