Convert message header to CamelCase

I am trying to convert the message header to CamelCase to create a twitter hashtag, I use a strip, but return an object instead. I do not know if this is correct?

# views.py def post_create(request): if not request.user.is_authenticated(): raise Http404 form_class = PostCreateForm if request.method == 'POST': form = form_class(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.creator = request.user instance.slug = slugify(instance.title) instance.hashtag = instance.title.strip() instance.save() slug = slugify(instance.title) return redirect(instance.get_absolute_url()) else: form = form_class() context = { 'form': form, } return render(request, "posts/post_create.html", context) 

What returns the <built-in method strip of unicode object at 0x031ECB48> in the var template, the result I'm looking for is similar to MyPostTitle in the template

  # Template view <h3>#{{instance.hashtag|title}}</h3> 

models.py

 class Post(models.Model): creator = models.ForeignKey(ProfileUser) title = models.CharField(max_length=80) hashtag = models.CharField(max_length=80) slug = models.SlugField(unique=True) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) 
+5
source share
3 answers
 >>> a = "foo baz bar" >>> "".join([s.capitalize() for s in a.rsplit()]) >>> FooBazBar 

To save:

 import re r = re.compile("[/!/?,:.;-]") t = r.sub(" ",instance.title) # clear punctuation instance.hashtag = "".join([s.capitalize() for s in t.rsplit()]) 
+3
source

strip removes spaces only from the beginning or end of a line ( https://docs.python.org/2/library/string.html#string.strip ). you can use

 instance.hashtag = instance.title.replace(' ', '') 

As a side note, it might be easier to add this functionality as a method to your model class:

 class Post(models.Model): ... def hashtag(self): if self.title is not None: return self.title.replace(' ', '') 
+4
source

The Python unicode class also has a title() method, which means you can:

 $ python3 >>> 'foo bar baz'.title() 'Foo Bar Baz' >>> 'foo bar baz'.title().replace(' ', '') 'FooBarBaz' 

Note that the order of .title().replace() important!

+1
source

Source: https://habr.com/ru/post/1242467/


All Articles