Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function for capping a string to a maximum length

Tags:

python

string

Is there a function in Python, built-in or in the standard library, for capping a string to a certain length, and if the length was exceeded, append three dots (...) after it?

For example:

>>> hypothetical_cap_function("Hello, world! I'm a string", 10)
"Hello, ..."
>>> hypothetical_cap_function("Hello, world! I'm a string", 20)
"Hello, world! I'm..."
>>> hypothetical_cap_function("Hello, world! I'm a string", 50)
"Hello, world! I'm a string"
like image 583
Hubro Avatar asked Jul 22 '12 17:07

Hubro


People also ask

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

How do I limit characters in Python?

Python's input function cannot do this directly; but you can truncate the returned string, or repeat until the result is short enough. # method 1 answer = input("What's up, doc? ")[:10] # no more than 10 characters # method 2 while True: answer = input("What's up, doc?

How do you store the length of a string in a variable in Python?

You need to use len() function to get length of a list, string.. In your code you are using raw_input(). raw_input() takes input and returns it as string .. so you need to convert your input string in list.


2 Answers

def cap(s, l):
    return s if len(s)<=l else s[0:l-3]+'...'
like image 179
Guy Adini Avatar answered Oct 22 '22 21:10

Guy Adini


Probably the most flexibile (short of just slicing) way is to create a wrapper around textwrap.wrap such as: (bear in mind though, it does try to be smart about splitting in some places which may not get exactly the result you're after - but it's a handy module to know about)

def mywrap(string, length, fill=' ...'):
    from textwrap import wrap
    return [s + fill for s in wrap(string, length - len(fill))]

s = "Hello, world! I'm a string"
print mywrap(s, 10)
# ['Hello, ...', 'world! ...', "I'm a ...", 'string ...']

Then just take the elements you're after.

like image 35
Jon Clements Avatar answered Oct 22 '22 22:10

Jon Clements