我有以下字符串:
This is example of a string which is longer than 30 characters
它的长度是62,我想将其限制为30。因此,简单的my_string [:30]的结果将是:
This is example of a string wh
我想得到:
This is example of a string
所以我想出了以下代码:
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
我的代码有效,但是我一直在思考是否有更好,更干净的方法来实现它。
答案 0 :(得分:3)
这是一种方法。
例如:
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
答案 1 :(得分:3)
您可以简化代码:
my_string[: index]
的字符串进行切片时,索引是否大于字符串大小无关紧要。rfind
方法(从末尾查找索引)来做到这一点。代码在这里:
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
在if
语句中,您可以检查index
是否为正(如果索引<0表示句子开头没有空格)。
答案 2 :(得分:0)
如果n>0
:
def limit(s,n): return s[:n-1-(s+" ")[n-1::-1].find(" ")]
测试:
for n in range(1,34): print(n,limit(s,n))
1 T
2 Th
3 Thi
4 This
5 This
6 This
7 This
8 This is
9 This is
10 This is
11 This is
12 This is
13 This is
14 This is
15 This is
16 This is example
17 This is example
18 This is example
19 This is example of
20 This is example of
21 This is example of a
22 This is example of a
23 This is example of a
24 This is example of a
25 This is example of a
26 This is example of a
27 This is example of a
28 This is example of a string
29 This is example of a string
30 This is example of a string
31 This is example of a string
32 This is example of a string
33 This is example of a string