How to concatenate items in a list to a single string

0 votes

Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?

E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence

sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
    sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str
Nov 17, 2020 in Python by kartik
• 37,520 points
603 views

1 answer to this question.

0 votes

Hello @kartik,

Use join:

>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'

Hope it helps!!

answered Nov 17, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How to convert each list item into string in a column of data frame. ?

Hey, To split a string you can use ...READ MORE

answered Feb 5, 2020 in Python by Roshni
• 10,480 points
914 views
+1 vote
2 answers

How to print first character of each word in upper case of a string in Python

class Solution:     def firstAlphabet(self, s):             self.s=s              k=''              k=k+s[0]              for i in range(len(s)):                     if ...READ MORE

answered Oct 28, 2020 in Python by Anurag
12,387 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,460 points
1,373 views
0 votes
1 answer

Combine list items to a string

>>> stmt = ['this','is','a','statement'] >>> ' '.join(sentence) 'this is ...READ MORE

answered Jun 7, 2018 in Python by Hamartia's Mask
• 1,580 points
640 views
+1 vote
12 answers
0 votes
1 answer

How to make a flat list out of list of lists?

Hii @kartik, Given a list of lists l, flat_list = ...READ MORE

answered Apr 13, 2020 in Python by Niroj
• 82,840 points
655 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP