Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation from a list of string, using a praticle in front and one at the end for each element

I have an array of strings:

data = ['a', 'b', 'c', 'd']

I want to obtain:

s.a, s.b, s.c, s.d

I tried:

"s., ".join(fields)

Doesn't work because I need s. in front and , at the end

like image 982
user3541631 Avatar asked Nov 04 '18 11:11

user3541631


People also ask

How do you concatenate a list of elements in a string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

Which method will you use to combine two strings into one text?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator.

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.


1 Answers

You should perform a mapping of the individual elements from 'x' to 's.x', we can do that by:

map('s.{}'.format, data)

then we can join these together by a comma:

', '.join(map('s.{}'.format, data))

this yields:

>>> ', '.join(map('s.{}'.format, data))
's.a, s.b, s.c, s.d'

Or like @JonClements says, since python-3.6, we can use literal string interpolation [PEP-498]:

', '.join(f's.{d}' for d in data)
like image 80
Willem Van Onsem Avatar answered Sep 28 '22 17:09

Willem Van Onsem