0

List needs to be converted to a string and perform a string operations,

Is there a effective way to convert both the operations into 1,

lista = ['col-1,','col-2,','col-3,']

stra = ' '.join(lista)

stra = stra.rstrip(',')
3
  • 1
    Why the .rstrip()? There are no commas in your Lista items.. Commented Oct 3, 2012 at 16:44
  • stra='a b c', there's no ,? Commented Oct 3, 2012 at 16:45
  • You've answered your own question. stra = ' '.join(lista) makes a string from a list. What more do you need? Commented Oct 3, 2012 at 16:45

5 Answers 5

2

How about ', '.join(['col-1', 'col-2', 'col-3'])? Then you don't need rstrip at all.

Sign up to request clarification or add additional context in comments.

3 Comments

But you cannot change the input data. Maybe he has to work with that.
Then again, maybe not. Perhaps he assumed join only works for single characters, and munged the data to add commas. Or maybe you're right and the data is provided in that form. We'll see :)
There is a comma after each col,['col-1,','col-2,'], the solution provided by @Rohit worked.
0

Since your join returns a string.. So, instead of storing it, you can chain one more method call...

stra = ' '.join(Lista).rstrip(',')

Or, better you can do this: -

stra = ' '.join(s.rstrip(',') for s in lista)

This will not print comma(,) in between your list items..

Comments

0

All string methods return new strings.

stra = " ".join(s.rstrip(",") for s in lista)

or if you only wanted to trim the last comma, just " ".join(lista).rstrip(",").

Comments

0

Since the join() method returns a string you can chain methods:

stra = ' '.join(lista).rstrip(',')  # prints col-1, col-2, col-3

Or, if you want to strip the commas before joining the strings (since you have the comma at the end of every string I'm assuming you want to):

stra = ' '.join(map(lambda s: s.rstrip(','), lista))  # prints col-1 col-2 col-3

or:

stra = ' '.join(s.rstrip(',') for s in lista)  # prints col-1 col-2 col-3

Comments

0

I'm not entirely sure what you mean by "convert both the operations into 1", but if you don't have any control over lista, and can rely on it being in the format specified, then just do

' '.join(lista)[:-1]

If you do have control over lista, then follow nneonneo's suggestion and get rid of the commas in the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.