import textwrap
string1 = "Alice is in wonderland"
string2 = "Bob is playing games on his computer"
new_string1 = textwrap.shorten(string1, 20, placeholder="")
new_string2 = textwrap.shorten(string2, 20, placeholder="")
print(new_string1) # Alice is in
print(new_string2) # Bob is playing games
{}唯一的缺点是它会压缩空间。如果您不希望发生这种情况,您可以实现自己的方法
def shorten(s, max_chars):
# Special case is the string is shorter than the number of required chars
if len(s) <= max_chars:
return s.rstrip()
stop = 0
for i in range(max_chars + 1):
# Always keep the location of the last space behind the pointer
if s[i].isspace():
stop = i
# Get rid of possible extra space added on the tail of the string
return s[:stop].rstrip()
string1 = "Alice is in wonderland"
string2 = "Bob is playing games on his computer"
new_string1 = shorten(string1, 20)
new_string2 = shorten(string2, 20)
print(new_string1) # Alice is in
print(new_string2) # Bob is playing games
这不是正则表达式的一个好用例。尽管如此,^{} 方法确实实现了这一点
{}唯一的缺点是它会压缩空间。如果您不希望发生这种情况,您可以实现自己的方法
相关问题 更多 >
编程相关推荐