Split the string from the end(str.rsplit
) only once and get the length of last item:
>>> s = """AAAAAAA
BBBB
CCCCC
DDD"""
>>> s.rsplit('\n', 1)
['AAAAAAA\n BBBB\n CCCCC', ' DDD']
#On the other hand simple str.split will split the string more than once:
>>> s.split('\n')
['AAAAAAA', ' BBBB', ' CCCCC', ' DDD']
Now simply get the length of last item:
>>> len(s.rsplit('\n', 1)[-1])
12
With bigger data this is going to be extremely fast:
>>> s = """AAAAAAA
BBBB
CCCCC
DDD"""
>>> s="\n".join([s]*1000) #4000 lines
>>> %timeit len(s.split('\n')[-1])
10000 loops, best of 3: 84.9 µs per loop
>>> %timeit len(s.splitlines()[-1])
10000 loops, best of 3: 91.3 µs per loop
>>> %timeit len(s.rsplit('\n', 1)[-1])
1000000 loops, best of 3: 1.62 µs per loop
1
solved python, count characters in last line string [closed]