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.
You can simplify the code:
my_string[: index], it's not a matter if the index is bigger than the string size.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).
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
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