[Tutor] Split Method
Peter Otten
__peter__ at web.de
Thu Jan 30 12:22:42 CET 2014
Rafael Knuth wrote:
> Hey there,
>
> I am having some issues with splitting strings.
> I already know how to split strings that are separated through empty
> spaces:
>
> def SplitMyStrings():
> Colors = "red blue green white black".split()
> return (Colors)
>
> print(SplitMyStrings())
>
>>>>
> ['red', 'blue', 'green', 'white', 'black']
>
> ... however I couldn't figure out how to split each character into a list
> item. This is what I want to get as a result:
>
>>>>
> ['r', 'e', 'd', 'b', 'l', 'u', 'e', 'g', 'r', 'e', 'e', 'n', 'w', 'h',
> 'i', 't', 'e', 'b', 'l', 'a', 'c', 'k']
>>> colors = "red blue green white black"
>>> list(colors)
['r', 'e', 'd', ' ', 'b', 'l', 'u', 'e', ' ', 'g', 'r', 'e', 'e', 'n', ' ',
'w', 'h', 'i', 't', 'e', ' ', 'b', 'l', 'a', 'c', 'k']
If you don't want the spaces remove them before
>>> list(colors.replace(" ", ""))
['r', 'e', 'd', 'b', 'l', 'u', 'e', 'g', 'r', 'e', 'e', 'n', 'w', 'h', 'i',
't', 'e', 'b', 'l', 'a', 'c', 'k']
or while
[c for c in colors if not c.isspace()]
['r', 'e', 'd', 'b', 'l', 'u', 'e', 'g', 'r', 'e', 'e', 'n', 'w', 'h', 'i',
't', 'e', 'b', 'l', 'a', 'c', 'k']
converting to a list. Note that c.isspace() is true for all whitespace
chars; use [... if c != " "] if you want to omit " " only.
More information about the Tutor
mailing list