Home » Concatenate Strings in python

Concatenate Strings in python

Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

Another common task with strings is to concatenate them , join them together

Table of Contents

Example 1

In the following example we ask the user for 2 strings and then concatenate them.
Note we add a space between the 2 strings, this is just in case the user does not do this

# Concatenate Strings
myString1 = input("Please Enter the First  String : ")
myString2 = input("Please Enter the Second String : ")

concatstring = myString1 + ' ' + myString2
print("Concatenated Strings = ", concatstring)

When you run this you will see something like this depending on your text

>>> %Run concatstring1.py
Please Enter the First  String : This is a
Please Enter the Second String : string to concatenate
Concatenated Strings =  This is a string to concatenate

Example 2

You can also concatenate string literals, lets see an example of this

# Python Program to Concatenate Strings
concatstring1 = 'This ' 'is ' 'a ' 'test'
print("Concatenate String 1 = ", concatstring1)

concatstring2 = ('This ' 'is ' 'a ' 'test')
print("Concatenate String 2 = ", concatstring2)

Run this and you will see the following

>>> %Run concatstring2.py
Concatenate String 1 = This is a test
Concatenate String 2 = This is a test

Note the spaces after the strings, miss this and you would see Thisisatest

Links

code is available at

https://github.com/programmershelp/maxpython/tree/main/code%20example/String%20examples

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More