Reputation: 25
I have to split characters from a text file which looks like this:
87965202,3127C4
87965221,2496B3
87965208,6703D3
87965155,5930B4
I have separated the lines at the commas. I just need some help with splitting the second part of the line into three separate characters. i.e. "3127", "C", "4"
This is my code so far:
for line in inputFile2:
parts = line.split(",")
info = parts[1]
Upvotes: 0
Views: 1054
Reputation: 1460
Or with a regular expression
import re
r = re.compile('([0-9]{4})([A-Z])([0-9])')
print r.findall('5930B4')
print r.findall('3127C4')
gives
[('5930', 'B', '4')]
[('3127', 'C', '4')]
Upvotes: 1
Reputation: 48297
Use regex for that:
info = parts[1]
info = "3127C4"
//use regex to match the no numeric char
indexChar = re.search("\D", info)
slice1 = values[0:indexChar]
slice2 = values[indexChar]
slice3 = values[indexChar:]
dont forget to import re
Upvotes: 0
Reputation: 17478
slice the string
info = []
for line in inputFile2:
parts = line.split(",")
info.append([parts[0], parts[1][:4], parts[1][4:5], parts[1][5:]])
Upvotes: -1
Reputation: 4321
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
Upvotes: 0
Reputation: 168856
If the 2nd part will always be of the form NNNNAN, then you can use slicing:
info = '2496B3'
info = info[0:4],info[4:5],info[5:6]
print(info)
# ('2496', 'B', '3')
If the pattern needs to be more general, try a regular expression:
import re
info = '249678ABBZ3'
re.split('([A-Z]+)', info)
# ['249678', 'ABBZ', '3']
Upvotes: 1