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'