Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Get First Letter of String

How can I get the first letter of a string in a template with Django? I tried using the truncatechars filter, but it adds an ellipsis at the end.

{{ stringvariable | truncatechars:1 }}  

I would like to go from "John" to "J".

like image 845
cusejuice Avatar asked Sep 12 '14 18:09

cusejuice


People also ask

How to capitalize the first character in a string in Django?

To capitalize the first character in a string in a Django template, use the built-in capfirst function. To use capfirst, pass it after a string using a | (pipe) like this: This is a string. That's it! You can now ensure strings start with a capital letter.

How to get first n characters from a string in Python?

Similarly, you can also use the slice notation to get the first n number of characters from a string. In this below example, we are getting the first 2 characters from a given string.

How do I get a single word from a string in Python?

You can use string slicing to get a single word from a string in Python Always remember the start index of Python is zero and Python always takes last string specified as n=n-1 Can I listen to SiriusXM for 3 months for free right now? Yes, you can. Stream SiriusXM for 3 months for free. See Offer Details. Is Python fast yet?

How do I know if I'm using Django or not?

If value is "I'm using Django", the output will be "I\'m using Django". Capitalizes the first character of the value. If the first character is not a letter, this filter has no effect. If value is "django", the output will be "Django".


1 Answers

You can use built-in slice template filter:

{{ stringvariable|slice:"1" }}

Demo:

>>> from django.template import Template, Context
>>> t = Template('{{ stringvariable|slice:"1" }}')
>>> c = Context({'stringvariable': 'John'})
>>> t.render(c)
u'J'
like image 93
alecxe Avatar answered Oct 03 '22 02:10

alecxe