About Django image upload handling

RegEx to replace char which shouldnt start and end with some char!! for both python and ?JavaScript


UseCase: Replace single occurrence of "_" which shouldn’t start and ends with "_".

mystr = "This_is_Something____funny__but_important" 
re.sub(r'(?<!_)(_(?!_))', '#', mystr) 
Note: If you want to modify for different char sets(for beginners)! replace below keywords
chars you want to play with.


var mystr = "This_is_Something____funny__but_important" 

mystr.replace(/([^_:])_(?!_)/g, '$1#'); 


Same here:

This is not the post to learn about python/java script.
Just a useful find for my pal abby Sheik. :)

Protocol relative URL / Scheme less URL advantages.

Nothing but all your URLs will be relative to the current page's protocol.
simple isn't it?

Just append URL(without protocol) with " // ", look at the example below.
Eg:   <img src="//yourdomain.com/imgs/icon.png"> 

Why do we need to use protocol relative URL / Scheme less URL 
If the browser is viewing current page through HTTPS, then it’ll request the resource(whose URL is scheme less) with the HTTPS protocol, otherwise it’ll request it with HTTP.
Yes same thing works for files which are viewed locally.
It’ll try to request the file with the file://protocol.

Read it if you want to understand meta-classes in python..

Link to the actual question and answer :  stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 

Classes as objects

Before understanding metaclasses, you need to master classes in Python. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language.
In most languages, classes are just pieces of code that describe how to produce an object. That's kinda true in Python too:
  >>> class ObjectCreator(object):
  ...       pass

  >>> my_object = ObjectCreator()
  >>> print my_object
  <__main__.ObjectCreator object at 0x8974f2c>
But classes are more than that in Python. Classes are objects too.
Yes, objects.
As soon as you use the keyword class, Python executes it and creates an OBJECT. The instruction

  >>> class ObjectCreator(object):
  ...       pass
creates in memory an object with the name ObjectCreator.
This object (the class) is itself capable of creating objects (the instances), and this is why it's a class.
But still, it's an object, and therefore:
  • you can assign it to a variable
  • you can copy it
  • you can add attributes to it
  • you can pass it as a function parameter
  >>> print ObjectCreator # you can print a class because it's an object
  <class '__main__.ObjectCreator'>
  >>> def echo(o):
  ...       print o
  >>> echo(ObjectCreator) # you can pass a class as a parameter
  <class '__main__.ObjectCreator'>
  >>> print hasattr(ObjectCreator, 'new_attribute')
  >>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
  >>> print hasattr(ObjectCreator, 'new_attribute')
  >>> print ObjectCreator.new_attribute
  >>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
  >>> print ObjectCreatorMirror.new_attribute
  >>> print ObjectCreatorMirror()
  <__main__.ObjectCreator object at 0x8997b4c>

Creating classes dynamically

Since classes are objects, you can create them on the fly, like any object.
First, you can create a class in a function using class:
  >>> def choose_class(name):
  ...     if name == 'foo':
  ...         class Foo(object):
  ...             pass
  ...         return Foo # return the class, not an instance
  ...     else:
  ...         class Bar(object):
  ...             pass
  ...         return Bar
  >>> MyClass = choose_class('foo') 
  >>> print MyClass # the function returns a class, not an instance
  <class '__main__.Foo'>
  >>> print MyClass() # you can create an object from this class
  <__main__.Foo object at 0x89c6d4c>
But it's not so dynamic, since you still have to write the whole class yourself.
Since classes are objects, they must be generated by something.
When you use the class keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually.
Remember the function type? The good old function that lets you know what type an object is:
>>> print type(1)
<type 'int'>
>>> print type("1")
<type 'str'>
>>> print type(ObjectCreator)
<type 'type'>
>>> print type(ObjectCreator())
<class '__main__.ObjectCreator'>
Well, type has a completely different ability, it can also create classes on the fly. type can take the description of a class as parameters, and return a class.
(I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backwards compatibility in Python)
type works this way:
  type(name of the class, 
       tuple of the parent class (for inheritance, can be empty), 
       dictionary containing attributes names and values)
>>> class MyShinyClass(object):
...       pass
can be created manually this way:
  >>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
  >>> print MyShinyClass
  <class '__main__.MyShinyClass'>
  >>> print MyShinyClass() # create an instance with the class
  <__main__.MyShinyClass object at 0x8997cec>
You'll notice that we use "MyShinyClass" as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things.
type accepts a dictionary to define the attributes of the class. So:
>>> class Foo(object):
...       bar = True
Can be translated to:
  >>> Foo = type('Foo', (), {'bar':True})
And used as a normal class:
  >>> print Foo
  <class '__main__.Foo'>
  >>> print Foo.bar
  >>> f = Foo()
  >>> print f
  <__main__.Foo object at 0x8a9b84c>
  >>> print f.bar
And of course, you can inherit from it, so:
  >>>   class FooChild(Foo):
  ...         pass
would be:
  >>> FooChild = type('FooChild', (Foo,), {})
  >>> print FooChild
  <class '__main__.FooChild'>
  >>> print FooChild.bar # bar is inherited from Foo
Eventually you'll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute.
>>> def echo_bar(self):
...       print self.bar
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
>>> hasattr(FooChild, 'echo_bar')
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.
This is what Python does when you use the keyword class, and it does so by using a metaclass.

What are metaclasses (finally)

Metaclasses are the 'stuff' that creates classes.
You define classes in order to create objects, right?
But we learned that Python classes are objects.
Well, metaclasses are what create these objects. They are the classes' classes, you can picture them this way:
  MyClass = MetaClass()
  MyObject = MyClass()
You've seen that type lets you do something like this:
  MyClass = type('MyClass', (), {})
It's because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes.
Now you wonder why the heck is it written in lowercase, and not Type?
Well, I guess it's a matter of consistency with str, the class that creates strings objects, and int the class that creates integer objects. type is just the class that creates class objects.
You see that by checking the __class__ attribute.
Everything, and I mean everything, is an object in Python. That includes ints, strings, functions and classes. All of them are objects. And all of them have been created from a class:
  >>> age = 35
  >>> age.__class__
  <type 'int'>
  >>> name = 'bob'
  >>> name.__class__
  <type 'str'>
  >>> def foo(): pass
  >>> foo.__class__
  <type 'function'>
  >>> class Bar(object): pass
  >>> b = Bar()
  >>> b.__class__
  <class '__main__.Bar'>
Now, what is the __class__ of any __class__ ?
  >>> a.__class__.__class__
  <type 'type'>
  >>> age.__class__.__class__
  <type 'type'>
  >>> foo.__class__.__class__
  <type 'type'>
  >>> b.__class__.__class__
  <type 'type'>
So, a metaclass is just the stuff that creates class objects.
You can call it a 'class factory' if you wish.
type is the built-in metaclass Python uses, but of course, you can create your own metaclass.

The __metaclass__ attribute

You can add a __metaclass__ attribute when you write a class:
class Foo(object):
  __metaclass__ = something...
If you do so, Python will use the metaclass to create the class Foo.
Careful, it's tricky.
You write class Foo(object) first, but the class object Foo is not created in memory yet.
Python will look for __metaclass__ in the class definition. If it finds it, it will use it to create the object class Foo. If it doesn't, it will use type to create the class.
Read that several times.
When you do:
class Foo(Bar):
Python does the following:
Is there a __metaclass__ attribute in Foo?
If yes, create in memory a class object (I said a class object, stay with me here), with the name Foo by using what is in __metaclass__.
If Python can't find __metaclass__, it will look for a __metaclass__ in Bar (the parent class), and try to do the same.
If Python can't find __metaclass__ in any parent, it will look for a __metaclass__ at the MODULE level, and try to do the same.
Then if it can't find any __metaclass__ at all, it will use type to create the class object.
Now the big question is, what can you put in __metaclass__ ?
The answer is: something that can create a class.
And what can create a class? type, or anything that subclasses or uses it.

Custom metaclasses

The main purpose of a metaclass is to change the class automatically, when it's created.
You usually do this for APIs, where you want to create classes matching the current context.
Imagine a stupid example, where you decide that all classes in your module should have their attributes written in uppercase. There are several ways to do this, but one way is to set __metaclass__ at the module level.
This way, all classes of this module will be created using this metaclass, and we just have to tell the metaclass to turn all attributes to uppercase.
Luckily, __metaclass__ can actually be any callable, it doesn't need to be a formal class (I know, something with 'class' in its name doesn't need to be a class, go figure... but it's helpful).
So we will start with a simple example, by using a function.
# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_attr):
    Return a class object, with the list of its attribute turned 
    into uppercase.

  # pick up any attribute that doesn't start with '__'
  attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
  # turn them into uppercase
  uppercase_attr = dict((name.upper(), value) for name, value in attrs)

  # let `type` do the class creation
  return type(future_class_name, future_class_parents, uppercase_attr)

__metaclass__ = upper_attr # this will affect all classes in the module

class Foo(): # global __metaclass__ won't work with "object" though
  # but we can define __metaclass__ here instead to affect only this class
  # and this will work with "object" children
  bar = 'bip'

print hasattr(Foo, 'bar')
# Out: False
print hasattr(Foo, 'BAR')
# Out: True

f = Foo()
print f.BAR
# Out: 'bip'
Now, let's do exactly the same, but using a real class for a metaclass:
# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type): 
    # __new__ is the method called before __init__
    # it's the method that creates the object and returns it
    # while __init__ just initializes the object passed as parameter
    # you rarely use __new__, except when you want to control how the object
    # is created.
    # here the created object is the class, and we want to customize it
    # so we override __new__
    # you can do some stuff in __init__ too if you wish
    # some advanced use involves overriding __call__ as well, but we won't
    # see this
    def __new__(upperattr_metaclass, future_class_name, 
                future_class_parents, future_class_attr):

        attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)

        return type(future_class_name, future_class_parents, uppercase_attr)
But this is not really OOP. We call type directly and we don't override call the parent __new__. Let's do it:
class UpperAttrMetaclass(type): 

    def __new__(upperattr_metaclass, future_class_name, 
                future_class_parents, future_class_attr):

        attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)

        # reuse the type.__new__ method
        # this is basic OOP, nothing magic in there
        return type.__new__(upperattr_metaclass, future_class_name, 
                            future_class_parents, uppercase_attr)
You may have noticed the extra argument upperattr_metaclass. There is nothing special about it: a method always receives the current instance as first parameter. Just like you have self for ordinary methods.
Of course, the names I used here are long for the sake of clarity, but like for self, all the arguments have conventional names. So a real production metaclass would look like this:
class UpperAttrMetaclass(type): 

    def __new__(cls, name, bases, dct):

        attrs = ((name, value) for name, value in dct.items() if not name.startswith('__'))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)

        return type.__new__(cls, name, bases, uppercase_attr)
We can make it even cleaner by using super, which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):
class UpperAttrMetaclass(type): 

    def __new__(cls, name, bases, dct):

        attrs = ((name, value) for name, value in dct.items() if not name.startswith('__'))
        uppercase_attr = dict((name.upper(), value) for name, value in attrs)

        return super(UpperAttrMetaclass, cls).__new__(cls, name, bases, uppercase_attr)
That's it. There is really nothing more about metaclasses.
The reason behind the complexity of the code using metaclasses is not because of metaclasses, it's because you usually use metaclasses to do twisted stuff relying on introspection, manipulating inheritance, vars such as __dict__, etc.
Indeed, metaclasses are especially useful to do black magic, and therefore complicated stuff. But by themselves, they are simple:
  • intercept a class creation
  • modify the class
  • return the modified class

Why would you use metaclasses classes instead of functions?

Since __metaclass__ can accept any callable, why would you use a class since it's obviously more complicated?
There are several reasons to do so:
  • The intention is clear. When you read UpperAttrMetaclass(type), you know what's going to follow
  • You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
  • You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
  • You can hook on __new__, __init__ and __call__. Which will allow you to do different stuff. Even if usually you can do it all in __new__, some people are just more comfortable using __init__.
  • These are called metaclasses, damn it! It must mean something!

Why the hell would you use metaclasses?

Now the big question. Why would you use some obscure error prone feature?
Well, usually you don't:
Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why).
Python Guru Tim Peters
The main use case for a metaclass is creating an API. A typical example of this is the Django ORM.
It allows you to define something like this:
  class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
But if you do this:
  guy = Person(name='bob', age='35')
  print guy.age
It won't return an IntegerField object. It will return an int, and can even take it directly from the database.
This is possible because models.Model defines __metaclass__ and it uses some magic that will turn the Person you just defined with simple statements into a complex hook to a database field.
Django makes something complex look simple by exposing a simple API and using metaclasses, recreating code from this API to do the real job behind the scenes.

The last word

First, you know that classes are objects that can create instances.
Well in fact, classes are themselves instances. Of metaclasses.
  >>> class Foo(object): pass
  >>> id(Foo)
Everything is an object in Python, and they are all either instances of classes or instances of metaclasses.
Except for type.
type is actually its own metaclass. This is not something you could reproduce in pure Python, and is done by cheating a little bit at the implementation level.
Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques:
  • monkey patching
  • class decorators
99% of the time you need class alteration, you are better off using these.
But 99% of the time, you don't need class alteration at all :-)

Access-control-allow-orign crosssite AJAX JSON requests. Overview !!

XMLHTTPRequest cannot load www.testexample.com origin is not allowed by Access-control-allow-orign I hope many of guys encounter this error when you do cross site AJAX request.

Well what is the need to block cross site ajax requests ?

The same origin policy has been implemented for the security reasons, since modern web apps extensively depends on the HTTP Cookies to maintain authenticated users sessions
there are possibilities that cookie/confidential data is compromised.
Hence it is needed to differentiate between the requests made by its own site and others through different domains.

more: http://en.wikipedia.org/wiki/Same_origin_policy

So how can we access json from other sites safely ?

Lets take a use case:
When i was building a RSS feed app (https://github.com/Narengowda/Feed/) where i wanted to build this app using pure JS, i ran in to these problems

1. How to access RSS (http://feeds.feedburner.com/NdtvNews-TopStories) from different sites which uses my Feed app?
2. How to convert to JSON ?

Parsing RSS XML and converting to JSON was easy tough i did it, But how to access RSS feeds ?
cant use JQuery's getJSON coz i wanted to buid Feed app using pure JS !!!

after goggling for sometime got to know about JSONP (http://en.wikipedia.org/wiki/JSONP)

The only tricky way to access JSON data is using <script> tag.
Yes the script tag loads what ever data which return from th URL which is specified in src attribute.

eg. <script src="www.test.com/json"> </script>

The very Important thing is XMLHTTPRequest to load 'scr' is not blocked eventough if the request is going cross site.

so there is a way we can load JSON somewere. yes JQuery's getJSON does the same thing.

fine how can i load XML? XML also can be loading using script tag but it leads to syntax errors...
Here i got another solution GOOGLE Feed api service (https://developers.google.com/feed/v1/jsondevguide) using this service i was able to parse and get JSON for any RSS feed.

eg url: https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://feeds.feedburner.com/NdtvNews-TopStories&num=50&callback=callbackfunctionafterload'

the above url returns Top stories as JSON. WOW!!!

And here is the code which helps get JSON using JSONP technique or simple use $.getJSON()

* Fetches feeds using google apis and JSONP.
* @param {string} i url URL to be fetched.
* @param {number} i num Number of feeds to request.
* @param {function} callback Callback to be called after json response.
function getFeed(url, num, callback) {
  gurl = 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=' +
    url + '&num=' + num + '&callback=' + callback.name;

* JSONP implementation in JS.
* @param {string} i url URL to be fetched.
function getJSON(url) {
  var head = document.head;
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;

In the URL you can see "callback=callbackfunctionafterload" what is this ??

This is the callback function which will be called when the script tag data is completely loaded, the callback function will be called with data loaded as argument to that function

and the callback will be like

function callback(data) {
  alert(data) // yey!!!  write your code to handle data.

Not every JSON URL's support callback feature !!
This support should be enabled from the serverside, in google feed api case it is enabled.
When you use $.getJSON() JQuery automatically appends some thing like this to the URL your are trying to access "callback=jquery3243434234", It creates some unique function so that it can call back to return data instead of loading data in script tag.

How to enable callback feature at serverside ???
I love Django :)

Here is the decorator function

courtesy : http://djangosnippets.org/snippets/2208/

from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

class AllowJSONPCallback(object):
    """This decorator function wraps a normal view function                                                                                     
    so that it can be read through a jsonp callback.                                                                                            
    def my_view_function(request):                                                                                                              
        return HttpResponse('this should be viewable through jsonp')                                                                            
    It looks for a GET parameter called "callback", and if one exists,                                                                          
    wraps the payload in a javascript function named per the value of callback.                                                                 
    Using AllowJSONPCallback implies that the user must be logged in                                                                            
    (and applies automatically the login_required decorator).                                                                                   
    If callback is passed and the user is logged out, "notLoggedIn" is                                                                          
    returned instead of a normal redirect, which would be hard to interpret                                                                     
    through jsonp.                                                                                                                              
    If the input does not appear to be json, wrap the input in quotes                                                                           
    so as not to throw a javascript error upon receipt of the response."""
    def __init__(self, f):
        self.f = login_required(f)

    def __call__(self, *args, **kwargs):
        request = args[0]
        callback = request.GET.get('callback')
        # if callback parameter is present,                                                                                                     
        # this is going to be a jsonp callback.                                                                                                 
        if callback:
            if request.user.is_authenticated():
                    response = self.f(*args, **kwargs)
                    response = HttpResponse('error', status=500)
                if response.status_code / 100 != 2:
                    response.content = 'error'
                response = HttpResponse('notLoggedIn')
            if response.content[0] not in ['"', '[', '{'] \
                    or response.content[-1] not in ['"', ']', '}']:
                response.content = '"%s"' % response.content
            response.content = "%s(%s)" % (callback, response.content)
            response['Content-Type'] = 'application/javascript'
            response = self.f(*args, **kwargs)
        return response

Happy cross site AJAX !!

"is" in python

How do you check two objects are same or not ?
Yes id() builtin function provides you the identity of an object, just compare it
>>> a = "helloo"
>>> id(a)
>>> b = a
>>> id(a) == id(b)
But the best pythonic way to check objects is use 'is' operator.
>>> a = "heloo" 
>>> b = a
>>> a is b
But what is happening in the below example ??
>>> i = 1
>>> j = 1
>>> i is j
Why True ? i and j are two different objects !!
 >>> k = 1.0
>>> l = 1.0
>>> k is l

Works fine along with float, but not with int ???
Yes python caches the values of string and int for better efficiency so int strings with same values
will have same id, and hence “is” operator returns true in case of int and string.

String Example showing same id for different objects:
>>> a = "apple" 
>>> b = "apple"
>>> id(a)
>>> id(b)

Feed JS Widget

Pure JS, Simple news widget....

How to use ?

<script src="https://rawgithub.com/Narengowda/Feed/master/feed.js"></script>

But put it inside the body !!!
As simple as it is!!

Best online JS HTML and CSS editors...

Best online JS HTML and CSS editors...


jsFiddle is a fresh tool that not only displays the code and highlights it but also executes its code within the browser for even better debugging. 




JS Bin is an open source collaborative web development debugging tool.
  • Write code and have it both save in real-time, but also render a full preview in real-time
  • Help debug other people's JavaScript, HTML or CSS by sharing and editing urls
  • CodeCast - where you share what you're typing in JS Bin in real-time
  • Remote rendering - view the output of your JS Bin on any device on any platform, updating in real-time
  • Processors, including: coffee-script, LESS, Markdown and Jade.
  • Debug remote Ajax calls



CodePen is a playground for the front end side of the web. It's all about inspiration, education, and sharing.
Need to build a reduced test case to demonstrate and figure out a bug? CodePen is great for that. Want to show off your latest creation and get feedback from your peers? CodePen is great for that. Want to find example of a particular design pattern for you project? CodePen is great for that.



Erbix offers productivity web apps for small businesses using an online apps platform (based on the JavaScript language). The apps offered include Pluto – an online team organizer and to-do manager, Eris – an interactive online form creator, and Meeting Planner – a new way to organize events and meetups democratically.
Anybody can write apps using JavaScript (and our browser-based IDE if they choose to). The JavaScript engine is based on RingoJS, an open-source server-side JavaScript engine. Erbix supports a web-based console which can interact via git and svn commands with external source version control repositories, or via SQL statements with a dedicated PostgreSQL database.


CSS Desk is an online free editing tool that combines the HTML and CSS concurrently. It’s very helpful for the beginners who are passionate towards web designing. This nifty tool provides you a real time output of how your code looks like as you type.
You can edit the CSS and HTML on the left panel and view the output on right. CSS Desk provides options to choose a default background color, reset your document and download your work as an HTML file. It also allows you to share the code with others.
Try this free handy tool !!






repl.it - Best python online interpreter


Its simple n I just love it :)

If you ever want to run python code and share it ?

Supports languages like Python Ruby, cofeescript, Javascript and many more.

With nice interface for writing code and also console..
Save your code and get unique URL to share it with frnds.
No login required.

Here is a screenshot of it.

Justify lines in python

How to Justify lines in python.
Want to align string center or left or right ?
ljust, center, rjust takes two parameter length of the output string and padding char.
Padding char is optional and default val is “ ”.

  • rjust
     >>> a.rjust(40, "_")
     >>> a.rjust(40)

  • ljust
     >>> a.ljust(40, "_")
     >>> a.ljust(40)
     heloo '”

  • center
     >>> a.center(40, "_")
     >>> a.center(40)
     heloo ”

write and execute python + shell script

Write n execute shell n python script in same file same time !!!!

Yes you can combine shell and python script in same file and also execute them.
All you need to do is open file write shebang line pointing to shell interpreter then write your shell script at last put this line exec python "$0" "$@" , When shell reaches the line exec python "$0" "$@", it causes the shell process to end and Python interpreter to be executed rest of the python code.

The lines between """:" and " """ are seen as a Python multi line string and ignored by python interpreter. And also it ignores shebang line #!/bin/sh looks like comment.

1 #!/bin/sh
3 """:"
4 echo "This is shell script.”
5 exec python "$0" "$@"
6 """
8 import sys, platform
9 print "You can write python script here !!!"
10 print "Python version: " + sys.version
11 print "Platform: " + platform.system() + platform.release()
12 sys.exit (0)

Play with python String, tricks

Play with String.

String Interpolation or inline assignment is the best and efficient way to concatenate strings rather than using + operator.
Some of the interesting tricks with string interpolation are listed below with console output.

  • You can write comments  between code, python Concatenates string even when strings are across multiple lines, provided braces.
        >>> ('Test ' 'this '  # this is comment
        ... 'in new line')
        'Test this in new line'

        >>> 'Test  this %s' %('string')
        'Test  this string
  •  Concatenates string on its own when they are in single line
        >>> 'Test '    'this '     'string'         Test this string'
  • Simply use Plus operator to concatinate.
        >>> 'Test '+'this '+'string'
        'Test this string' 
  • Supports * operator to multiply them.
        >>> 'string ' * 10        'string string string string string string string string string string '
  • Interpolate across lines
        >>> ('Test  this %s '        ...   'in multiple lines') %('string')
        'Test  this string in multiple lines'
  • Write comments between statements while doing interpolation.
        >>> ('Test this %s '  # this is comment         ... 'in new line') %('new string')        'Test this new string in new line'
  • Use dictionary to interpolate.
        >>> "This is %(old)s and this is another %(new)s" % {'old': 'string', 'new': 'trick'}
        'This is string and this is another trick'
  •  If you have many declared variable in your local scope, Just do this.
        >>> var_one = "Heloo"        >>> var_two = "Haaiii"
        >>> 'What are we sayin ? %(var_one)s %(var_two)s' % locals()
        'What are we sayin ? Heloo Haaiii'

  • A new formatting way by using format method in string class.
      >>> name = "Naren"
      >>> age = 24
      >>> place = "Bengaluru"
      >>> a = "My name is {name} ,my age is {age} and i live in {place}" 

      >>> a.format(name=name, age=age, place=place)
      'My name is Naren ,my age is 24 and i live in Bengaluru'