How do I concatenate (join) items in a list to a single string?
Use str.join
:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
Best way to concatenate List of String objects?
Your approach is dependent on Java's ArrayList#toString() implementation.
While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better).
Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.
python: concatenate integer items in a list to a single string
Im not sure what you mean by better, but you could try this.
''.join([str(x) for x in my_list])
Concatenate elements of a list
Use str.join()
:
s = ''.join(l)
The string on which you call this is used as the delimiter between the strings in l
:
>>> l=['a', 'b', 'c']
>>> ''.join(l)
'abc'
>>> '-'.join(l)
'a-b-c'
>>> ' - spam ham and eggs - '.join(l)
'a - spam ham and eggs - b - spam ham and eggs - c'
Using str.join()
is much faster than concatenating your elements one by one, as that has to create a new string object for every concatenation. str.join()
only has to create one new string object.
Note that str.join()
will loop over the input sequence twice. Once to calculate how big the output string needs to be, and once again to build it. As a side-effect, that means that using a list comprehension instead of a generator expression is faster:
slower_gen_expr = ' - '.join('{}: {}'.format(key, value) for key, value in some_dict)
faster_list_comp = ' - '.join(['{}: {}'.format(key, value) for key, value in some_dict])
Concatenate the items of a list into one list item
Does this work:
a = [['a','b'],['c', 'd'], ['e', 'f']]
out = []
for item in a:
out.append(["".join(item)])
print (out)
Output:
[['ab'], ['cd'], ['ef']]
how do I concatenate string with list in list items?
Assuming you start with
a = ['apple',['green', 'red', 'yellow']]
Then a[0]
is a string, and a[1]
is a list of strings. You can change a[1]
into a string using ', '.join(a[1])
, which will concatenate them using a comma and a space.
So
a[0] + ' available in ' + ', '.join(a[1])
should work, as you can concatenate strings with +
.
How to concatenate items in a list?
Loop over your list items, building strings. Whenever the current item ends in a period, append the currently built string to the final result, and start building a new string:
l=["First item","Second item","Third item.","Fourth item."]
result = []
curr_str = ""
for item in l:
curr_str += item
if item[-1] == ".":
result.append(curr_str)
curr_str = ""
['First itemSecond itemThird item.', 'Fourth item.']
How do you concatenate a string to every element of a list?
If you are interested in all the links you can unlist
link_2
and paste them together.
indeed <- "https://www.indeed.com"
result <- paste0(indeed, unlist(link_2))
If you want to maintain the list structure in link_2
use lapply
-
result <- lapply(link_2, function(x) paste0(indeed, x))
Write a function that accepts a list of strings and concatenates them
In Python, you can just use the +
operator to concatenate two strings. In your case, you can do something like this:
def concat(list_args):
res = ""
for w in list_args:
res += w
return res
Then if you run
print(concat(['a', 'bcd', 'e', 'fg']))
you get abcdefg
Concat all strings inside a Liststring using LINQ
Warning - Serious Performance Issues
Though this answer does produce the desired result, it suffers from poor performance compared to other answers here. Be very careful about deciding to use it
By using LINQ, this should work;
string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));
class description:
public class Foo
{
public string Boo { get; set; }
}
Usage:
class Program
{
static void Main(string[] args)
{
string delimiter = ",";
List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };
Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
Console.ReadKey();
}
}
And here is my best :)
items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)
Related Topics
Limiting Floats to Two Decimal Points
Why Is the Output of My Function Printing Out "None"
How to Use Threading in Python
Convert a String Representation of a Dictionary to a Dictionary
Get Statistics For Each Group (Such as Count, Mean, etc) Using Pandas Groupby
Rolling or Sliding Window Iterator
Why Are Multiple Instances of Tk Discouraged
How to Force Division to Be Floating Point? Division Keeps Rounding Down to 0
Why Isn't the 'Global' Keyword Needed to Access a Global Variable
Does Python Have a String 'Contains' Substring Method
A Non-Blocking Read on a Subprocess.Pipe in Python
Local Variables in Nested Functions
How to Type Hint a Method With the Type of the Enclosing Class