Python limit string length format

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]?

asked Oct 23, 2014 at 15:40

Łukasz RogalskiŁukasz Rogalski

20.8k8 gold badges54 silver badges89 bronze badges

1

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.]

answered Oct 23, 2014 at 16:26

4

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'

answered Oct 23, 2014 at 15:45

2

I had the same question and came up with this solution using LogRecordFactory.

orig_factory = logging.getLogRecordFactory[]

def record_factory[*args, **kwargs]:
    record = orig_factory[*args, **kwargs]
    record.sname = record.name[-10:] if len[
        record.name] > 10 else record.name
    return record

logging.setLogRecordFactory[record_factory]

Here I am truncating the name to 10 characters and storing it in the attribute sname, which can be used as any other value.

%[sname]10s

It is possible to store the truncated name in record.name, but I wanted to keep the original name around too.

answered Jul 6, 2018 at 6:25

1

Format a string limiting its length in Python #

Use a formatted string literal to format a string and limit its length, e.g. result = f'{my_str:5.5}'. You can use expressions in f-strings to limit the string's length to a given number of characters.

Copied!

my_str = 'bobbyhadz' # ✅ limit string length to 5 characters result = f'{my_str:5.5}' print[result] # 👉️ 'bobby' # 👇️ limit string length removing excess trailing characters result = my_str[:5] print[result] # 👉️ 'bobby' # 👇️ limit string length removing excess leading characters result = my_str[-5:] print[result] # 👉️ 'yhadz'

The first example uses a formatted string literal to limit a string's length.

Formatted string literals [f-strings] let us include expressions inside of a string by prefixing the string with f.

Copied!

var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print[result] # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

Copied!

my_str = 'bobbyhadz' result = f'{my_str:5.5}' print[result] # 👉️ 'bobby'

The digit right after the colon is the width to format the string to.

The string gets left-padded with spaces if necessary.

Copied!

my_str = 'b' result = f'{my_str:5.5}' print[repr[result]] # 👉️ 'b '

If you don't want to pad the string with spaces if it is shorter, remove the digit after the colon.

Copied!

my_str = 'bobbyhadz' result = f'{my_str:.5}' print[result] # 👉️ bobby

The digit after the period is the maximum size of the string.

The example formats the string to a maximum of 5 characters.

Alternatively, you can use string slicing.

Copied!

my_str = 'bobbyhadz' # 👇️ limit string length removing excess trailing characters result = my_str[:5] print[result] # 👉️ 'bobby' # 👇️ limit string length removing excess leading characters result = my_str[-5:] print[result] # 👉️ 'yhadz'

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive [up to, but not including].

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len[my_str] - 1.

If you need to only get the first N characters of a string, specify a stop index of N.

Copied!

my_str = 'bobbyhadz' result = my_str[:5] print[result] # 👉️ 'bobby'

The stop index is exclusive [up to, but not including], so the slice only consists of the first 5 characters of the string.

If you need to get the last N characters of a string, specify a start index of -N.

Copied!

my_str = 'bobbyhadz' result = my_str[-5:] print[result] # 👉️ 'yhadz'

Negative indices can be used to count backwards, e.g. my_str[-3:] returns the last 3 characters in the string.

If you need to pad the string with spaces to a fixed length, use the str.ljust and str.rjust[] methods.

Copied!

my_str = 'b' result = my_str[-3:].ljust[3] print[repr[result]] # 👉️ 'b ' result = my_str[-3:].rjust[3] print[repr[result]] # 👉️ ' b'

The str.ljust method pads the end of the string to the specified width with the provided fill character.

If no fill character is specified, the string gets padded with spaces.

The str.rjust method pads the beginning of the string to the specified width with the provided fill character.

How do I restrict the length of a string 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].

What is %s and %D Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example [for python 3] print ['%s is %d years old' % ['Joe', 42]] Would output Joe is 42 years old.

What does {: 3f mean in Python?

"f" stands for floating point. The integer [here 3] represents the number of decimals after the point. "%. 3f" will print a real number with 3 figures after the point. – Kefeng91.

How do you trim a string in Python?

Python Trim String.
strip[]: returns a new string after removing any leading and trailing whitespaces including tabs [ \t ]..
rstrip[]: returns a new string with trailing whitespace removed. ... .
lstrip[]: returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string..

Chủ Đề