Python string into characters

days_64

Python64

Posted on March 1, 2020

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']
      >>>
💖 💪 🙅 🚩
days_64
Python64

Posted on March 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024