开发者

Txt Parsing in Python

开发者 https://www.devze.com 2023-03-22 06:46 出处:网络
I know this is an easy one but I am brand new to programming and any help would be greatly appreciated.

I know this is an easy one but I am brand new to programming and any help would be greatly appreciated.

I have a text file that has a bunch of numbers in it (one per line). I need to open the file and split the number into three. If the number is "123456" i need to split it into "14","25","36" in other words I need it to go (x1x2), (y1y2), (z1,z2) for a number x1y1z1x2y2z2. For odd numbers I want to add a zero to the last group to even it out. Thanks for th开发者_如何学Goe help, I am hopeless at programming.


One simple suggestion. Covert your number to a list and operate on the elements of the list.

>>> list("123456")
['1', '2', '3', '4', '5', '6']
>>> 

Now, it would much easier for you to handle. If not, then you should perhaps start with some Python tutorials.


This should satisfy your example:

s = "123456"
ss = [s[i::3] for i in range(3)]
ss
> ['14', '25', '36']

To make sure the strings are equal length, you can either pad the original string:

s = s.ljust((len(s)+2)//3 * 3, '0')

or do:

l = (len(s)+2)//3
ss = [s[i::3].ljust(l, '0') for i in range(3)]


So because you're slicing into thirds, the problem isn't odd numbers, but is rather numbers not divisible by 3. Here's a function that accepts a string and returns a tuple of slices of that string.

def triplet(s):
    extra_zeros = (3 - len(s)) % 3
    s += '0' * extra_zeros
    return (s[::3], s[1::3], s[2::3])

Here's a demonstration of its behavior:

>>> triplet('123456')
('14', '25', '36')
>>> triplet('1234567')
('147', '250', '360')
>>> triplet('12345678')
('147', '258', '360')
>>> triplet('123456789')
('147', '258', '369')
0

精彩评论

暂无评论...
验证码 换一张
取 消