我必须从文本文件中拆分字符,如下所示:
87965202,3127C4
87965221,2496B3
87965208,6703D3
87965155,5930B4
我用逗号分隔了这些行。我只需要帮助将线的第二部分分成三个单独的字符。 即" 3127"," C"," 4"
到目前为止,这是我的代码:
for line in inputFile2:
parts = line.split(",")
info = parts[1]
答案 0 :(得分:1)
如果第二部分的形式总是为NNNNAN,那么你可以使用切片:
info = '2496B3'
info = info[0:4],info[4:5],info[5:6]
print(info)
# ('2496', 'B', '3')
如果模式需要更通用,请尝试使用正则表达式:
import re
info = '249678ABBZ3'
re.split('([A-Z]+)', info)
# ['249678', 'ABBZ', '3']
答案 1 :(得分:1)
或使用正则表达式
if @report_comment.save(report_comment_params)
给出
import re
r = re.compile('([0-9]{4})([A-Z])([0-9])')
print r.findall('5930B4')
print r.findall('3127C4')
答案 2 :(得分:0)
secondHalf = "5930B4"
#slicing format is string[start:end:step]
initialNumber = secondHalf[0:4] #start at character 0 and end at character 4
middleLetter = secondHalf[4:5] #start at character 4 and end at character 5
endingNumber = secondHalf[-1:] #start from the last character
print(initialNumber, middleLetter, endingNumber)
#output: 5930 B 4
答案 3 :(得分:0)
使用正则表达式:
keyring
别忘了导入重新
答案 4 :(得分:0)
您在谈论这个:info[8:12]
?
答案 5 :(得分:-1)
切割字符串
info = []
for line in inputFile2:
parts = line.split(",")
info.append([parts[0], parts[1][:4], parts[1][4:5], parts[1][5:]])