1

I hope to convert a list of strings to a list of a long string. For example, I hope to convert ['c++', 'python', 'sklearn', 'java'] to ["'c++', 'python', 'sklearn', 'java'"]. Namely, the original list have some strings, the target list should have a long string which includes the small string.

I have tried the ' '.join([str(elem) for elem in s]), but the results are not in a list.

s = ['c++', 'python', 'sklearn', 'java']
listToStr = ' '.join([str(elem) for elem in s])
print listToStr

The expected output is:

["'c++', 'python', 'sklearn', 'java'"]

The actual output is:

c++ python sklearn java
1
  • 4
    I can't resist asking why you would want to do this. Commented Sep 27, 2019 at 22:10

2 Answers 2

4

This can be done using one line of code and no loop/join by turning the list to a string and taking the brackets off. Then wrap it in a list.

print [str(s)[1:-1]]
Sign up to request clarification or add additional context in comments.

Comments

2

Join it with commas, add the single quotes and put it in a list:

myList= [", ".join(["'"+elem+"'" for elem in s])]

3 Comments

I believe it should be ", ".join... based on his question.
thanks, it should add the single quote and add "," before join.
Not creating the inner list and using .format would be much more efficient. It also removes the burden of doing str(elem) (which I'm not sure why you did. Inputs are clearly strings) [", ".join("'{}'".format(elem) for elem in s)]

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.