Mojo vs Python: Comparison with Examples - Part II: Files and Strings

enter image description here

This article is part of a series that I dedicate to comparing Mojo with Python. If you want to read about what Mojo is, how to get started or the previous article of this series, you can check my previous articles.

Examples of File and String Operations

You can find the complete code in my GitHub repository dedicated to comparing Mojo with Python.

Let’s dive into the examples. I will first show the code in Python so that you know exactly what I wanted to achieve in Mojo.

File

Python:

# writing to the file
with open("input/input.txt", 'w') as f:
    f.write("Mojo\nis\nthe\nbest")

# reading the file
with open("input/input.txt", 'r') as f:
    file_content = f.read()
print(file_content)
print("Lines:")
with open("input/input.txt", 'r') as f:
    line = f.readline()
    while line:
        print(line.strip())
        line = f.readline()
# lines = file_content.split('\n')
# for i in range(len(lines)):
#     print(lines[i])
Mojo
is
the
best
Lines:
Mojo
is
the
best

Mojo:

# writing to the file
with open("input/input.txt", 'w') as f:
    f.write(String("Mojo\nis\nthe\nbest"))

# reading the file
var file_content: String = String()
with open("input/input.txt", 'r') as f:
    file_content = f.read()
print(file_content)
print("Lines:")
var lines: List[String] = file_content.split('\n')
for i in range(len(lines)):
    print(lines[i])
Mojo
is
the
best
Lines:
Mojo
is
the
best

Mojo currently supports only r and w file operation modes. Also, in Mojo it is not supported by the file standard library to read a file line by line. The simpler solution is to read the whole file and split it by the newline character, or for a more sophisticated solution we can use FileHandle's read_bytes method.

String

Python:

s1 = "abcba"
s2 = " happy coding in Mojo  "

print("Characters in s1:")
for c in s1:
    print(c)
# for i in range(len(s1)):
#     print(s1[i])
print("First two characters:", s1[0:2])
print("Last character:", s1[-1])
print("Every second character:", s1[::2])
print("Number of 'a':", s1.count('a'))
print("First 'b' from the left:", s1.find('b', 0))
print("First 'b' from the right:", s1.rfind('b', 0))
print(s1.replace('c', 'x'))

print(s2.strip())
print(s2.rstrip())
print(s2.strip().upper())
print(s2.strip().lower())

s2_words = s2.strip().split(' ')
for word in s2_words:
    if word.startswith("ha"):
        print("HAPPY")
    if word.endswith("jo"):
        print("MOJO")

joined = " and ".join([s1, s2])
print(joined)
print(" - ".join(s2_words))  # does not work in Mojo (yet?)
Characters in s1:
a
b
c
b
a
First two characters: ab
Last character: a
Every second character: aca
Number of 'a': 2
First 'b' from the left: 1
First 'b' from the right: 3
abxba
happy coding in Mojo
 happy coding in Mojo
HAPPY CODING IN MOJO
happy coding in mojo
HAPPY
MOJO
abcba and  happy coding in Mojo  
happy - coding - in - Mojo

Mojo:

var s1: String = String("abcba")
var s2: String = String()
s2 = " happy coding in Mojo  "

print("Characters in s1:")
for i in range(len(s1)):
    print(s1[i])
print("First two characters:", s1[0:2])
print("Last character:", s1[-1])
print("Every second character:", s1[::2])
print("Number of 'a':", s1.count('a'))
print("First 'b' from the left:", s1.find('b', 0))
print("First 'b' from the right:", s1.rfind('b', 0))
print(s1.replace('c', 'x'))

print(s2.strip())
print(s2.rstrip())
print(s2.strip().upper())
print(s2.strip().lower())

var s2_words: List[String] = s2.strip().split(' ')
for word in s2_words:
    if word[].startswith("ha"):
        print("HAPPY")
    if word[].endswith("jo"):
        print("MOJO")

var joined: String = String(" and ").join(s1, s2)
print(joined)
Characters in s1:
a
b
c
b
a
First two characters: ab
Last character: a
Every second character: aca
Number of 'a': 2
First 'b' from the left: 1
First 'b' from the right: 3
abxba
happy coding in Mojo
 happy coding in Mojo
HAPPY CODING IN MOJO
happy coding in mojo
HAPPY
MOJO
abcba and  happy coding in Mojo

In these examples I used only String, but Mojo also includes the StringLiteral.
In Python we can just loop through the characters of a string with a for..in loop, in Mojo it is not the case. Slicing and most of the string functions work pretty much the same way though. While in Python the split() function by default splits a string by space, in Mojo you have to specify it. A notable difference is that in Mojo we cannot provide a list of strings as an argument for the join() function. I hope it will change in the future.
Apart from these, the overlap between Mojo and Python remains significant.

After the first two articles we can still acknowledge that Mojo is quite Pythonic and there are only a few differences. At least at this level. But there are differences, and there will be. Let’s not forget that they are different programming languages after all. Anyway, let’s wait and see what changes will happen to files and strings in Mojo.

This article ends here, but the next one is already on the way. We will take a look at a speed comparison. Good luck on your journey with Mojo and Happy Coding! 🔥🔥🔥

Comments