Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Pythonic way to concatenate strings

Given this harmless little list:

>>> lst = ['o','s','s','a','m','a'] 

My goal is to pythonically concatenate the little devils using one of the following ways:

A. plain ol' string function to get the job done, short, no imports

>>> ''.join(lst) 'ossama' 

B. lambda, lambda, lambda

>>> reduce(lambda x, y: x + y, lst) 'ossama' 

C. globalization (do nothing, import everything)

>>> import functools, operator >>> functools.reduce(operator.add, lst) 'ossama' 

Please suggest other pythonic ways to achieve this magnanimous task.

Please rank (pythonic level) and rate solutions giving concise explanations.

In this case, is the most pythonic solution the best coding solution?

like image 267
random guy Avatar asked Jan 25 '10 16:01

random guy


People also ask

What is the most efficient way to concatenate many strings together in Python?

The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

Is join faster than concatenation Python?

String join is significantly faster then concatenation.

What is the time complexity of concatenation?

String concatenation It can be a bit surprising, but this code actually runs in O(N2) time. The reason is that in Java strings are immutable, and as a result, each time you append to the string new string object is created.


2 Answers

''.join(lst) 

the only pythonic way:

  • clear (that what all the big boys do and what they expect to see),
  • simple (no additional imports needed, stable across all versions),
  • fast (written in C) and
  • concise (on an empty string join elements of iterable!).
like image 70
SilentGhost Avatar answered Sep 21 '22 12:09

SilentGhost


Have a look at Guido's essay on python optimization, it covers converting lists of numbers to strings. Unless you have a good reason to do otherwise, use the join example.

like image 35
Dana the Sane Avatar answered Sep 21 '22 12:09

Dana the Sane