Shoryu
Shoryu

Reputation: 225

How to split a string into characters in python?

I know that:

print(list('Hello'))

will print

['H', 'e', 'l', 'l', 'o']

and I know that

print(list('Hello world!'))

will print

['Hello', 'world!']

What syntax would be easiest to get:

['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']

Upvotes: 1

Views: 36780

Answers (2)

xiyurui
xiyurui

Reputation: 231

work under python 3.6

 a = "Hello world!"
 listresp = list(map(list, a))
 listff =[]
 print (listresp)
 for charersp in listresp:
     for charfinnal in charersp:
         listff.append(charfinnal)
 print (listff)


 ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']

Upvotes: 2

falsetru
falsetru

Reputation: 368894

list('Hello world!') gives what you want, not ['Hello', 'world!'].

>>> print(list('Hello world!'))
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']

I think you confused the output of str.split:

>>> print('Hello world!'.split())
['Hello', 'world!']

Upvotes: 16

Related Questions