Rumman
Rumman

Reputation: 113

How to split a word into letters in Python

I was wondering if there is a straightforward way to do the following:

Input string:

input = 'Hello'

Output string:

output = 'H,e,l,l,o'

I understand you can do list(input), but that returns a list and I wanted to get the string rather than the list.

Any suggestions?

Upvotes: 7

Views: 18978

Answers (3)

Rushy Panchal
Rushy Panchal

Reputation: 17532

Since NPE already provided the ','.join('Hello') method, I have a different solution (though it may not be more Pythonic):

inputStr, outputStr = 'hello', ''
for char in inputStr: outputStr += char + ','
print outputStr[:-1]

Output: 'h,e,l,l,o'.

Upvotes: 1

PaulMcG
PaulMcG

Reputation: 63729

outputstr = ','.join(inputstr)

Upvotes: 6

NPE
NPE

Reputation: 500367

In [1]: ','.join('Hello')
Out[1]: 'H,e,l,l,o'

This makes use of the fact that strings are iterable and yield the individual characters when iterated over.

Upvotes: 21

Related Questions