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"
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.
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?
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.
def cap(s, l):
return s if len(s)<=l else s[0:l-3]+'...'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With