Another common task with strings is to concatenate them , join them together
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