Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to limit words in string basing on number of characters

Tags:

python

I have a following string:

This is example of a string which is longer than 30 characters

Its length is 62 and I want to limit it to 30. So result of simple my_string[:30] would be:

This is example of a string wh

and I would like to get:

This is example of a string

So I came up with following code:

def func(my_string):
    if len(my_string) > 30:
        result_string = []
        for word in my_string.split(" "):
            if len("".join(title)) + len(word) <= 30:
                result_string.append(word)
            else:
                return result_string
    return my_string

My code works, however I keep thinking if there is a better and more clean way to do it.

like image 910
Adam Harmasz Avatar asked Jan 23 '26 22:01

Adam Harmasz


2 Answers

You can simplify the code:

  • The first if statement can be avoided. When you are slicing a string like: my_string[: index], it's not a matter if the index is bigger than the string size.
  • Then you just need to check if the character where you cut the string is a space or not. If it's not, you need to find the previous space. You can do it with the rfind method (find index from the end).

Here the code:

def slice_string(text, size):
    # Subset the 'size' first characters
    output = text[:size]
    if len(text) > size and text[size] != " ":
        # Find previous space index
        index = output.rfind(" ")
        # slice string
        output = output[:index]
    return output

text = "This is example of a string which is longer than 30 characters"

print(slice_string(text, 30))
# This is example of a string

In the if statement, you can check if the index is positive or not (if index < 0 means there is no space in the beginning of the sentence).

like image 103
Alexandre B. Avatar answered Jan 25 '26 12:01

Alexandre B.


This is one approach.

Ex:

s = "This is example of a string which is longer than 30 characters "
def func(my_string):
    result = ""
    for item in my_string.split():                 #Iterate each word in sentence
        temp = "{} {}".format(result, item).strip() #Create a temp var
        if len(temp) > 30:                          #Check for length
            return result
        result = temp
    return result

print(func(s))  #This is example of a string
like image 42
Rakesh Avatar answered Jan 25 '26 10:01

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!