0

I'm trying to separate a string to its characters.

e.x: "hello world!" to ["h", "e", "l", "l", "o", " ", "w", ... , "!"]

I tried .split() but it just separates words.

what should I do?

iammgt
  • 43
  • 1
  • 10

2 Answers2

2

Code:

list("hello world!")

Output:

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
Cobra
  • 200
  • 9
1

There are a couple ways you could go about this!

The easiest:

Like @RomanPerekhrest said, using list("hello world!") would create a list of all the elements in the string. This is definitely the ideal answer.

Doing it the hard way:

If you want to get fancy (which is not better in this case but I wanted to include it for completeness), you could also do a list comprehension. This would look like

result = [x for x in "hello world!"]

This will take each element in "hello world!" and append it to a list, and return that in the variable result.

ladygremlin
  • 452
  • 3
  • 14