String Merge (String concatenation)
String concatenation means the operation of joining two strings. It is also known as string merge. In Python programming, two strings can be merged (concatenated) using the + operator.
>>> 'Python' + 'Practicals'
'PythonPracticals'#Multiple strings are automatically merged
>>> 'Python''Practicals'
'PythonPracticals'
>>> 'Ahmedabad''Gujarat''India'
'AhmedabadGujaratIndia'
This works only with two literals; a variable and a string can’t be merged directly. Look at the example given below:
>>> str = 'Python'
>>> str 'Practicals'
SyntaxError: invalid syntax>>> str 'Practicals'
>>> (str*2) 'Practicals'
SyntaxError: invalid syntaxTo concatenate a variable and a string literal, use + operator as shown below:
>>> str = 'Python'
>>> str + 'Practicals'
PythonPracticals>>> str + 'Practicals'
# expression + a string is valid
>>> (str*2) + 'Practicals'
'PythonPythonPracticals'
Multiplying String with * Operator
String can be repeated using * operator in Python. Check the following example:
>>> 3 * 'Python '
'Python Python Python '
>>> 2 * 'Practicals '
'Practicals Practicals '
* * * * *
No comments:
Post a Comment