Python String Concatenation and String Formatting

Nov 30, 2016

2 mins read

Published in

Python String Concatenation is the process for joining small string to make the bigger. For example, you can create a full name by joining two string-like Firstname and Lastname. Formatting will help to display variable in or end of the string.

Python String Concatenation

Python provides the easy way to concatenate Strings by using + (plus)  and * (star) Sign. There are other methods such as append(), join() and format().

**Using + **

  • will adds values on either side of the operator

Here is an example :

1
2
3
4
>>> str1 = "Jhon"
>>> str2 = "Doe"
>>> print str1 + " " + str2
Jhon Doe

**Using ***

  •  Creates new strings, concatenating multiple copies of the same string.

Here is an example :

1
2
>>> "John" * 3
'JohnJohnJohn'

String Formatting in Python

You might have the experience to use C language to print String and Integer using %s and %d. Python has similar string formatting to create new, formatted strings. The % operator is used to format variables.

Here are the examples:

1
2
3
4
>>> name = "John Doe"
>>> print "Hello, %s How are you?" % name
Hello, John Doe How are you?
>>>

String formatting using two and more than values using the tuple. A tuple is a sequence of immutable Python objects. Tuples use parentheses.

1
2
3
4
5
6
7
>>> name = "John Doe"
>>> salary = 10000
>>> period = "Month"
>>> print "%s earns %d per month." % (name, salary)
John Doe earns 10000 per month.
>>> print "%s earns %d per %s." % (name, salary, period)
John Doe earns 10000 per Month.

Python is supporting other function like append and join to manipulate String data.

Related Python Articles:

Read JSON File using Python Code and Prompt

JSON Pretty Print using Python- with Examples

Check out this Python code Formatter

Sharing is caring!