0

Say that you had this: Laugh = 'hehe' The practicality of this of example doesn't really matter but if you wanted to put laugh into a list by doing: laugh = list(laugh) and you do laugh[1] = 'a'. How would you put laugh into 'hahe'?

Spike
  • 29
  • 3

2 Answers2

2

In general, to convert a list into a string, use ''.join:

laugh = 'hehe'
laugh = list(laugh)
laugh[1] = 'a'

laugh = ''.join(laugh)

This is better than other methods such as using a for-loop:

new_laugh = ''
for c in laugh:
    new_laugh += c
iz_
  • 15,923
  • 3
  • 25
  • 40
0

The simplest way (using just the + operator - in case you want to have a user defined function to do get the task done) would be to add the components of the list into one string:

def string_to_list(L):
    S = ""
    for i in L:
        S = S + str(L)
    return S
string_to_list(laugh)

You can also use the join() function, to do the same:

Laugh = ''.join(laugh)
Eshita Shukla
  • 791
  • 1
  • 8
  • 30
  • 1
    Really, `+` is just as much a built-in function as `str.join` is. There is no reason to write that loop. – chepner Mar 02 '19 at 05:12
  • The `+` is not a function, it is an operator. And, I have specified both ways... Just gave the options (that I know about) – Eshita Shukla Mar 02 '19 at 11:05
  • 1
    Yes, but it’s implemented by an add function built in in to the type. – chepner Mar 02 '19 at 13:49
  • Oh! Okay.. Fair point. I just meant to say that I would always prefer `2+3` rather than `sum(2,3)`. Maybe that wasn't clear. But, thanks. I will edit the answer accordingly – Eshita Shukla Mar 02 '19 at 17:06
  • My main point is that while the `for` loop is useful for describing how `join` works, you would never actually want to use it in preference to `join`. – chepner Mar 02 '19 at 18:46