How do you read a character array in python?


Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Try it Yourself »




I have a text file that consists of some text.

I want to import this into an array consisting of characters, Ex: a file containing "Hello" would become

['h', 'e', 'l', 'l', 'o'].

I tried using loadtxt (which I usually use for reading data from files) but I think it can only handle actual data (with numbers and stuff). How do I do it?

tshepang

11.7k21 gold badges90 silver badges134 bronze badges

asked Nov 11, 2013 at 15:22

4

This is the usual way to read an entire file:

with open("file") as f:
    content = f.read()

You can then call list(content) to get a list from the string.

answered Nov 11, 2013 at 15:24

rnintyrninty

1,0876 silver badges10 bronze badges

1

If you want to load strings using loadtxt:

import numpy as np
text = np.loadtxt(filepath, dtype = np.str)

As others are mentioning, there are other ways of doing this. Furthermore, you can access the individual characters of a string in much the same way as a list.

answered Nov 11, 2013 at 15:24

MagsolMagsol

4,59011 gold badges44 silver badges67 bronze badges

2

Perhaps you can just loop through the file using list comprehension:

[i for i in file.read()]

Or just convert the string to list:

char_list = list(file.read())

Keep in mind that this will include special characters, such as tabs and newlines.

answered Nov 11, 2013 at 15:23

aIKidaIKid

24.8k4 gold badges38 silver badges65 bronze badges

If NigntCell.txt is your data file and you want to get that text file into a list like as you asked then you could simply use list(content) as rninty suggested. Otherwise if you want to remove the white space from the file then you can use the below code:

file = open('NigntCell.txt', 'r')

char_list = list(file.read())

space = 0

char_list_len = len(char_list)

for i in range(char_list_len):

    if char_list[i] == ' ':
        space +=1 
    #for other than space add your respective 'counter' code here

for i in range(space):

    char_list.remove(' ')

You can remove other unnecessary characters like '\n' and so, similar to white space above.

answered Nov 11, 2013 at 19:03

praba230890praba230890

2,10420 silver badges36 bronze badges

In this article, we will learn to convert a given string into an array of characters in Python. We will use some built-in functions and some custom codes as well. Let's first have a quick look over what is a string in Python.

Python String

The string is a type in python language just like integer, float, boolean, etc. Data surrounded by single quotes or double quotes are said to be a string. A string is also known as a sequence of characters.

string1 = "apple"
string2 = "Preeti125"
string3 = "12345"
string4 = "pre@12"

Converting a string to a character array basically means splitting each character. This comma-separated character array will be a list of characters. List prints a string into comma-separated values. Each character will represent each index value.

Let us look at the different ways below to convert a string to a character array.

Example: Convert String to Character Array Using For loop

This example uses for loop to convert each character of string into comma-separated values. It prints a list of characters separated by a comma. It encloses the for loop within square brackets [] and splits the characters of the given string into a list of characters.

string = "studytonight"

to_array = [char for char in string]

print(to_array)


['s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't']

Example: Convert String to Character Array Using list

This example uses list keyword to convert a string to a character array. We can use a list to convert to any iterable. This is known as typecasting of one type to another. Python built-in list() function typecast the given string into a list. list() takes the string as an argument and internally changes it to an array.

string = "studytonight"

to_array = list(string)

print(to_array)


['s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't']

Example: Convert String to Character Array Using extend()

This method uses extend() to convert string to a character array. It initializes an empty array to store the characters. extends() uses for loop to iterate over the string and adds elements one by one to the empty string. The empty string prints a list of characters.

string = "studytonight"

#empty string
to_array = []

for x in string:
    to_array.extend(x)

print(to_array)


['s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't']

Conclusion

In this article, we learned to convert a given string into a character array. We used three approaches for the conversion such as for loop, list() and extend(). We used custom codes as well to understand the working.

How do I read a char array in Python?

“array char input in python” Code Answer's.
# number of elements..
n = int(input("Enter number of elements : ")).
# Below line read inputs from user using map() function..
a = list(map(int,input("\nEnter the numbers : "). strip(). split()))[:n].
print("\nList is - ", a).

How do you read an array of strings in Python?

How to access array elements? You can access array elements using the array index. The array element index start with 0 as like python list. ... .
Negative Indexing. You can also access the array element using the negative index. ... .
How to Iterate on Python Array. We can iterate on a python array using for loop..

How do I make a character array in Python?

Split String to Char Array in Python.
Use the for Loop to Split a String Into Char Array in Python..
Use the list() Function to Split a String Into Char Array in Python..
Use the extend() Function to Split a String Into Char Array in Python..
Use the unpack Method to Split a String Into Char Array in Python..

How do you input a list of characters in Python?

In python, to accept the inputs from the user, you can use input() function. Using this function, you can accept a string, integer or even a single character.