Python String Concatenation | DigitalOcean (2024)

String Concatenation is a very common operation in programming. Python String Concatenation can be done using various ways. This tutorial is aimed to explore different ways to concatenate strings in a python program.

We can perform string concatenation in the following ways:

  • Using + operator
  • Using join() method
  • Using % operator
  • Using format() function
  • Using f-string (Literal String Interpolation)

String Concatenation using + Operator

This is the most simple way of string concatenation. Let’s look at a simple example.

s1 = 'Apple's2 = 'Pie's3 = 'Sauce's4 = s1 + s2 + s3print(s4)

Output: ApplePieSauce Let’s look at another example where we will get two strings from user input and concatenate them.

s1 = input('Please enter the first string:\n')s2 = input('Please enter the second string:\n')print('Concatenated String =', s1 + s2)

Output:

Please enter the first string:HelloPlease enter the second string:WorldConcatenated String = HelloWorld

Python String Concatenation | DigitalOcean (1) It’s very easy to use + operator for string concatenation. However, the arguments must be a string.

>>>'Hello' + 4Traceback (most recent call last): File "<input>", line 1, in TypeError: can only concatenate str (not "int") to str

We can use str() function to get the string representation of an object. Let’s see how to concatenate a string to integer or another object.

print('Hello' + str(4))class Data: id = 0 def __init__(self, i): self.id = i def __str__(self): return 'Data[' + str(self.id) + ']'print('Hello ' + str(Data(10)))

Output:

Hello4Hello Data[10]

The biggest issue with + operator is that we can’t add any separator or delimiter between strings. For example, if we have to concatenate “Hello” and “World” with a whitespace separator, we will have to write it as "Hello" + " " + "World".

String concatenation using join() function

We can use join() function to concatenate string with a separator. It’s useful when we have a sequence of strings, for example list or tuple of strings. If you don’t want a separator, then use join() function with an empty string.

s1 = 'Hello's2 = 'World'print('Concatenated String using join() =', "".join([s1, s2]))print('Concatenated String using join() and whitespaces =', " ".join([s1, s2]))

Output:

Concatenated String using join() = HelloWorldConcatenated String using join() and spaces = Hello World

String Concatenation using the % Operator

We can use % operator for string formatting, it can be used for string concatenation too. It’s useful when we want to concatenate strings and perform simple formatting.

s1 = 'Hello's2 = 'World's3 = "%s %s" % (s1, s2)print('String Concatenation using % Operator =', s3)s3 = "%s %s from JournalDev - %d" % (s1, s2, 2018)print('String Concatenation using % Operator with Formatting =', s3)

Output:

String Concatenation using % Operator = Hello WorldString Concatenation using % Operator with Formatting = Hello World from JournalDev - 2018

String Concatenation using format() function

We can use string format() function for string concatenation and formatting too.

s1 = 'Hello's2 = 'World's3 = "{}-{}".format(s1, s2)print('String Concatenation using format() =', s3)s3 = "{in1} {in2}".format(in1=s1, in2=s2)print('String Concatenation using format() =', s3)

Output:

String Concatenation using format() = Hello-WorldString Concatenation using format() = Hello World

Python String format() function is very powerful, using it just for concatenation of strings is not its proper use.

String Concatenation using f-string

If you are using Python 3.6+, you can use f-string for string concatenation too. It’s a new way to format strings and introduced in PEP 498 - Literal String Interpolation.

s1 = 'Hello's2 = 'World's3 = f'{s1} {s2}'print('String Concatenation using f-string =', s3)name = 'Pankaj'age = 34d = Data(10)print(f'{name} age is {age} and d={d}')

Output:

String Concatenation using f-string = Hello WorldPankaj age is 34 and d=Data[10]

Python f-string is cleaner and easier to write when compared to format() function. It also calls str() function when an object argument is used as field replacement.

Conclusion

Python String formatting can be done in several ways. Use them based on your requirements. If you have to concatenate sequence of strings with a delimited, then use join() function. If some formatting is also required with concatenation, then use format() function or f-string. Note that f-string can be used with Python 3.6 or above versions. You can also learn more about python list concatenation.

Python String Concatenation | DigitalOcean (2024)
Top Articles
What Is GPU Mining And How Does It Work? | Mudrex Learn
Aflac Supplemental Insurance
Uhauldealer.com Login Page
Aadya Bazaar
The Best Classes in WoW War Within - Best Class in 11.0.2 | Dving Guides
Big Y Digital Coupon App
Bros Movie Wiki
6th gen chevy camaro forumCamaro ZL1 Z28 SS LT Camaro forums, news, blog, reviews, wallpapers, pricing – Camaro5.com
United Dual Complete Providers
R/Afkarena
7 Low-Carb Foods That Fill You Up - Keto Tips
Cvs Appointment For Booster Shot
065106619
Craighead County Sheriff's Department
Honda cb750 cbx z1 Kawasaki kz900 h2 kz 900 Harley Davidson BMW Indian - wanted - by dealer - sale - craigslist
Copart Atlanta South Ga
Accuweather Mold Count
Indiana Wesleyan Transcripts
67-72 Chevy Truck Parts Craigslist
Yisd Home Access Center
Bjerrum difference plots - Big Chemical Encyclopedia
Understanding Gestalt Principles: Definition and Examples
From This Corner - Chief Glen Brock: A Shawnee Thinker
Marilyn Seipt Obituary
Vht Shortener
Learn4Good Job Posting
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Golden Tickets
Bozjan Platinum Coins
Petsmart Distribution Center Jobs
Marine Forecast Sandy Hook To Manasquan Inlet
Hair Love Salon Bradley Beach
Exploring The Whimsical World Of JellybeansBrains Only
Montrose Colorado Sheriff's Department
Autozone Locations Near Me
Collier Urgent Care Park Shore
Babbychula
Pokemon Reborn Locations
Puretalkusa.com/Amac
Keir Starmer looks to Italy on how to stop migrant boats
San Bernardino Pick A Part Inventory
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Www.craigslist.com Waco
Conan Exiles Colored Crystal
Star Sessions Snapcamz
Ty Glass Sentenced
Blog Pch
Google Flights Missoula
Santa Ana Immigration Court Webex
Call2Recycle Sites At The Home Depot
Fredatmcd.read.inkling.com
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5928

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.