DEV Community

Cover image for Python string into characters
Python64
Python64

Posted on

Python string into characters

If you have text (string) in Python, you can break that up into a bunch of characters. There are several ways to do that.

In this article we'll discuss Python methods for processing a text string, for each character individually.

Processing a string into a character list

Use list(str)
If you have a string, you can turn it into characters by calling the list() function, this turns it into a list.

      >>> a = 'abcdefg'
      >>> list(a)
      [ 'a', 'b', 'c', 'd', 'e', ​​'f', 'g']
      >>> aList = list(a)
      >>> for item in aList:
          print (item) # Here you can add other operations, we simply use print
      a
      b
      c
      d
      e
      f
      g
      >>>

Use for traversal strings    
The for loop lets you loop over a strings characters. This iterates over every character in the string, where item is your character.

      >>> a = 'abcdefg'
      >>> for item in a:
              print (item) # Here you can add other operations, we simply use print   
      
      a
      b
      c
      d
      e
      f
      g
      >>>

list tricks you can use 
You can use the code below to breakup a string too

      >>> a = 'abcdefg'
      >>> result = [item for item in a]
      >>> result
      [ 'a', 'b', 'c', 'd', 'e', ​​'f', 'g']
      >>>

Top comments (1)

Collapse
 
mohsin708961 profile image
{{7*7}}

Awesome