Jump to content

Can strings be stored as arrays? For example, can "Hello" be stored as [H, e, l, l, o]?


SubhanUllah

Recommended Posts

 

The individual letters would all have to be strings if that string “Hello” were to be pieced out into what would be now be stored as a list [“H”, “e”, “l”, “l”, “o”], and no longer as a string. Because to begin with, your [H, e, l, l, o] wouldn't be recognised by Python. Let's check the type; it will produce an error…

print(type([H, e, l, l, o])) 
 
#OUTPUT (Error) 
NameError: name 'H' is not defined 
If those letters were say numbers or booleans, then they'd be recognised. E.g. [1, 2, 3, 4, 5]

So from your string “Hello”, what you could do is to piece it out into a list with a list() casting…

thestring = "Hello" 
thelist = list(thestring) 
 
print(thelist) 
#OUTPUT 
['H', 'e', 'l', 'l', 'o'] 
If you want your string back, as in getting back a string form from thelist, that'd be yet another story, such as using the .join()…

thelist = ['H', 'e', 'l', 'l', 'o'] 
 
thestringback = "".join(thelist) 
 
print(thestringback) 
#OUTPUT 
Hello 
 
print(type(thestringback)) 
<class 'str'> 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...