Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string formatting - limit string length, but trim string beginning

I'm using Python standard logging module with custom formatter where I limit length of some fields. It uses standard % Python operator.

I can apply limit for percent-formatted string like this (this limits length to 10 chars):

>>> "%.10s" % "Lorem Ipsum"
'Lorem Ipsu'

Is it possible to trim it from the beginning, so the output is 'orem Ipsum' (without manipulating right-side argument)?

like image 909
Łukasz Rogalski Avatar asked Oct 23 '14 15:10

Łukasz Rogalski


People also ask

How do you trim a string to a specific length in Python?

Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].

How do I limit characters in a string in Python?

use this: while True: answer = input("What's up, doc? ") if len(answer) >= 10: print("Too much info - keep it shorter!


2 Answers

Is it possible to trim it from the beginning with % formatting?

Python's % formatting comes from C's printf.

Note that the . indicates precision for a float. That it works on a string is a mere side effect, and unfortunately, there is no provision in the string formatting specification to accommodate stripping a string from the left to a fixed max width.

Therefore if you must strip a string to a fixed width from the end, I recommend to slice from a negative index. This operation is robust, and won't fail if the string is less than 10 chars.

>>> up_to_last_10_slice = slice(-10, None)
>>> 'Lorem Ipsum'[up_to_last_10_slice]
'orem Ipsum'
>>> 'Ipsum'[up_to_last_10_slice]
'Ipsum'

str.format also no help

str.format is of no help here, the width is a minimum width:

>>> '{lorem:>10}'.format(lorem='Lorem Ipsum')
'Lorem Ipsum'
>>> '{lorem:*>10}'.format(lorem='Lorem')
'*****Lorem'

(The asterisk, "*", is the fill character.)

like image 129
Russia Must Remove Putin Avatar answered Sep 30 '22 07:09

Russia Must Remove Putin


This can easily be done through slicing, so you do not require any string format manipulation to do your JOB

>>> "Lorem Ipsum"[-10:]
'orem Ipsum'
like image 41
Abhijit Avatar answered Sep 30 '22 07:09

Abhijit