English 中文(简体)
谷歌应用引擎:如何截断给定字符数后的字符串
原标题:Google App Engine: How to Truncate string after a given number of chars

我使用Django模板在谷歌应用程序Eninge上。

I want to truncate string after a given number of chars, for example, if a string (a title of a post) is too long, "This is a long long long long title", I want to display the first few words, like this: "This is a long long ..."

我在这里找到了一些Django代码片段:http://djangosnippets.org/snippets/1259/http://djangosnippets.org/snippets/763/一

我想知道:

  1. Google App Engine python中是否有更简单的解决方案?

  2. How can I use this snippet http://djangosnippets.org/snippets/1259/ in App Engine? I believe messing source code is not a good idea.

我需要在Django模板中截断字符串,而不是在python源代码中。类似这样的内容:{{string|truncatesmart:50}}

最佳回答

从您对问题的描述来看,这似乎是纯CSS已经专门解决的情况。请查看文本溢出:省略号属性,它截断一段文本以适应所需的宽度,并像你提到的那样放置一个尾随省略号(…)。我希望这将是一个更简单的解决方案,你不必重新发明轮子。

问题回答

您在django代码段中找到的truncatesmart函数是纯python,您可以在应用引擎中使用它而无需更改。

截断字符串的Python代码是:string=string[:chars],其中string是要修改的字符串,chars是字符数的整数值。

你链接到的代码段很棒,正如@voscasa所提到的,如果你在寻找比截断X个字符更聪明的东西,可以直接在python中使用。





相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签