-1

How do I split a string's letters? For example, I want 'Hello World' into 'h e l l o w o r l d'. I tried using the .split method but it only split the words, not all the characters. Is there any way I can do that?

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0

This should do it:

letters = [c for c in 'Hello World' if c != ' ']

Result:

['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
constantstranger
  • 9,176
  • 2
  • 5
  • 19
  • this isn't the desired output – Nin17 May 23 '22 at 19:48
  • I interpreted the question as wanting to do something similar to what `split` does but on a letter-by-letter basis, and `split` returns a list. As to what output was desired, I don't think anyone but OP can be the final authority. – constantstranger May 23 '22 at 20:18
  • ' I want 'Hello World' into 'h e l l o w o r l d'.'? – Nin17 May 23 '22 at 20:19
  • Yep, that's what was written, and also "How do I split a string's letters?" I don't think a string that separates letters with single spaces has "split" them. There is some ambiguity in the question, and my answer reflects my interpretation given that ambiguity. I suppose your answer reflects your interpretation. But that doesn't make either of us an authority on what was the desired output. – constantstranger May 23 '22 at 20:22
  • yeah well in general if OP said I want this into that then I'd take that to mean they want that regardless of the terminology used in the rest of the question – Nin17 May 24 '22 at 01:23
0

You should use join and a generator expression:

strng = 'Hello World'
' '.join(i.lower() if i != ' ' else '' for i in strng)

Output:

'h e l l o  w o r l d'
Nin17
  • 2,821
  • 2
  • 4
  • 14