Elements of a String

Hi,

I am new to mojo. I try to get the bytes of a String and their types as follows. But it gives a “no matching method in call to ‘_getitem_’” error. How can I fix it? I am using pip installed Mojo 0.26.1.0 (156d3ac6) on Ubuntu, Pytho 3.12.

ahmet

fn main():

var list = [“123”, “ab3”, “extra”]

for item in list:

for i in range(len(item)):

print(item[i], item[i].is_alpha())

Hi @ahmetax :slight_smile:
So to get the byte of a String, you can use

So your code would be updated to be the following:

fn main():
    var list = [“123”, “ab3”, “extra”]
    for item in list:
        for i in range(len(item)):
            # either
            var byte = item[byte=i]
            # or 
            var byte = item.as_bytes()[i]

Thanks a lot! Then, how can I check ‘byte’ is whether a number or alpha?

I found the following solution for the type of byte:

```mojo
fn main():
    var list = ["123", "ab3", "extra"]
    for item in list:
        for i in range(len(item)):
            # either
            var byte = item[byte=i]   # as characters
            # or 
            var byte2 = item.as_bytes()[i]   # as numbers
            print(byte, byte2, byte.is_ascii_digit())
```

1 Like