For 9 long years, the world has been submerged in the deepest of shadows, robbing every object and living creature of their color. Once a thriving civilization, the people have forgotten the warmth of the sun, the joy of laughter and the promise of a prosperous future.
Many brave souls have tried to venture inside the corrupting depths of Talos Castle, a long-abandoned orphanage from which the curse stemmed, but with each futile attempt, resignation became the daily fare for the people, all hope lost. Except for one person.
Armed with little other than her halberd and sheer nerve, Europa's daunting quest is clear: enter the castle, find the source of darkness, and return color to the lands before it is too lat
F-String Python Hex, Oct, and Bin: Efficient Number Conversions
5/5 – (1 vote)
As a Python developer, I’ve always been fascinated by the simplicity and versatility of the language. Python has always been my go-to language for all my programming needs, from its clean syntax to the vast array of libraries available. I recently had to work on a project requiring me to convert numbers to their hexadecimal, octal, and binary representations. While there are several ways to do this in Python, I discovered the f-string Python Hex, Oct, and Bin methods, which turned out to be the most efficient and straightforward approach. In this blog post, I’ll share my personal experience with this method and show you how to use it to convert numbers efficiently.
A Short Overview (Promised)
Python’s f-strings, also known as “formatted string literals”, have been introduced in Python 3.6 and offer a more efficient and readable way to format strings. They improve upon the older string formatting methods, such as using %-formatting and the str.format() method.
One of the key advantages of f-strings is their ability to handle various numeric representations, such as hexadecimal (hex), octal (oct), and binary (bin).
Handling hex, oct, and bin values in Python with f-strings is quite simple, thanks to the built-in support for these number systems. These can easily be incorporated into f-strings by using specific format specifiers within curly braces that contain the expressions to be evaluated and formatted at runtime. This allows you to seamlessly integrate hexadecimal, octal, and binary values into their strings without resorting to clumsier methods or additional function calls.
When working with f-strings in Python, you can use {variable:x} for hex, {variable:o} for oct, and {variable:b} for bin.
F-String Basics
One powerful feature of f-strings is their ability to format numbers in different bases, such as hexadecimal (hex), octal (oct), and binary (bin). To represent numbers in these formats, you can use the appropriate format specifier:
Hexadecimal: {x:X}
Octal: {x:o}
Binary: {x:b}
For example, to convert an integer into its hexadecimal representation, you can use the following f-string:
x = 255
hex_string = f"x in hex is: {x:X}"
print(hex_string) # Output: "x in hex is: FF"
Similarly, for octal and binary representations, you can use the respective format specifiers within the f-string:
x = 255
oct_string = f"x in oct is: {x:o}"
bin_string = f"x in bin is: {x:b}"
print(oct_string) # Output: "x in oct is: 377"
print(bin_string) # Output: "x in bin is: 11111111"
Using f-strings, you can create more readable and efficient code when working with different number systems in Python .
To format a number in hexadecimal with f-strings, you can use the format specifier {variable:x}. If you want zero padding, use the format specifier {variable:0Nx}, where N is the desired number of digit characters.
x = 255
hex_string = f"0x{value:02x}"
# Output: "0xff"
Similarly, to format a number in octal representation, use the format specifier {variable:o}.
y = 63
octal_string = f"0o{y:03o}"
# Output: "0o077"
For binary representation, you can use the format specifier {variable:b}.
z = 10
binary_string = f"0b{z:04b}"
# Output: "0b1010"
In addition to numerical formats, you can also use other format specifiers like:
Decimal: {variable:d}
Floating-point: {variable:.Nf} (where N is the number of decimal places to round)
Percentage: {variable:.N%}
Hexadecimal Representation
You can easily represent numbers in hexadecimal notation using f-strings in Python. Hexadecimal is a base-16 numeric system that uses sixteen distinct symbols – 0-9 representing zero to nine and A-F for ten to fifteen. It is widely used in computer programming and digital electronics.
You can use the format specifier within curly braces to convert a number to its hexadecimal representation using f-strings. For example:
number = 255
hex_num = f"{number:x}"
print(hex_num) # Output: "ff"
The same can be achieved using the format() function:
You can also include the 0x prefix by using the # flag in the format specifier:
number = 255
hex_num = f"{number:#x}"
print(hex_num) # Output: "0xff"
Hexadecimal representation can be helpful in various situations, such as when working with colors in CSS or addressing memory locations in computer systems.
Octal Representation
In Python, working with octal representations is smooth and straightforward thanks to built-in functions and f-strings. An octal number system has a base of 8, which means it uses eight symbols: 0, 1, 2, 3, 4, 5, 6, and 7. Converting between decimal and octal values can be accomplished with ease.
To obtain the octal representation of an integer in Python, simply use the oct() function. This function takes an integer as input and returns its octal representation as a string:
octal_value = oct(42) # 42 in decimal equals '0o52' in octal
With f-strings, you can elegantly include octal values directly in your strings. To do this, use the format specifier {value:#o} within an f-string:
number = 42
formatted_string = f"The octal representation of {number} is {number:#o}"
# Output: "The octal representation of 42 is 0o52"
Here are some essential points to remember when working with octal representations in Python:
Octal literals can be defined by adding a 0o prefix to the number: octal_number = 0o52.
Using arithmetic operations on octal numbers works the same as on decimal numbers: result = 0o52 + 0o10.
Convert between integer and octal string representations with the int() and oct() functions, respectively.
Binary Representation
In Python, f-strings are a convenient option for formatting strings, which can be used for various purposes like binary, octal, and hexadecimal representations. In this section, we’ll focus on the binary representation using f-strings.
To display a binary value of an integer using f-strings, you can use the formatting specifier b followed by the variable you want to convert inside the curly braces. The syntax looks like this: f"{variable:b}".
As an example, let’s say we want to display the binary representation of the number 5:
number = 5
binary_representation = f"{number:b}"
print(binary_representation) # Output: 101
Now, you can use a loop to display binary representations for a range of numbers. Let’s say we want to print binary values for numbers 0 to 5:
for i in range(6): print(f"{i} in binary is {i:08b}")
This will output the following:
0 in binary is 00000000
1 in binary is 00000001
2 in binary is 00000010
3 in binary is 00000011
4 in binary is 00000100
5 in binary is 00000101
Note the use of 08b within the f-string. The number 8 indicates the minimum width, and leading zeros are used to fill any remaining space. This ensures that binary values are displayed with a consistent width, making the output easier to read.
Conversion Functions
This section will focus on Python’s f-string capabilities for converting between hexadecimal, octal, and binary number systems. The primary goal is to make these conversions as simple as possible using f-string syntax.
Int to Hex, Oct, and Bin
When working with integers, you can easily convert them to their corresponding hexadecimal, octal, and binary representations using f-string formatting. Here are some examples:
This simple f-string syntax allows you to convert integers to their corresponding representation within an f-string using the 'x', 'o', and 'b' format specifiers.
String to Hex, Oct, and Bin
For converting strings to their hexadecimal, octal, and binary representations, you can use the following approach:
import binascii text = "Hello, World!" # Convert the string to bytes
text_bytes = text.encode('utf-8') # Use binascii to convert bytes to hex, oct, and bin
hex_string = binascii.hexlify(text_bytes).decode('utf-8')
oct_string = "".join([f"{char:o}" for char in text_bytes])
bin_string = "".join([f"{char:08b}" for char in text_bytes])
In this example, we first convert the string to bytes using the 'utf-8' encoding. Then we utilize the binascii module to convert bytes to their hexadecimal representation. We use list comprehension and f-string formatting for octal and binary conversions to achieve the same result.
Incorporating f-strings allows you to conveniently and efficiently perform conversions between various number systems in Python. This technique can be particularly beneficial when dealing with data representation and manipulation tasks.
Formatting Specifiers and F-Strings
The formatted string literals allow you to embed expressions inside the string, which are evaluated and formatted using the __format__ protocol.
Formatting numbers in hex, oct, and bin is quite easy with f-strings. Here are some examples:
Hexadecimal: f"{number:x}"
Octal: f"{number:o}"
Binary: f"{number:b}"
You have the option to add formatting specifiers and padding to your f-Strings. For instance, you can center the output and add zero-padding:
f" {data:^14s}" .format(f" {data:#04x}")
This snippet first converts the data to hexadecimal using {data:#04x} and then centers the output with {data:^14s} (from Stack Overflow).
Here’s a brief table that demonstrates how to format numbers using f-Strings:
Type
Example
Output
Hexadecimal
f"{15:x}"
f
Octal
f"{15:o}"
17
Binary
f"{15:b}"
1111
Utilizing f-Strings and various formatting specifiers can help you efficiently manage complex string formatting tasks in your Python projects .
To keep boosting your Python skills and stay on track with the emerging technologies of the exponential age (e.g., ChatGPT), check out our free cheat sheets and email academy here:
How to grab Alwa's Awakening - Go to the home page of https://www.gog.com/#giveaway - Login and Register - Go to the home page again - Wait for 10 seconds then start searching for Alwa's Awakening - on the home page look for "Deal of the Day" (there should be a banner below or above it) - on the banner there is a button "Yes, and claim the game" click it - That's it
War was rampaging all over the land for decades. In a desperate move to end it all, the mages provoked The Cataclysm. Massive balls of pure magic obliterated nearly everything. A strange purple mist propagated everywhere. They say that those who entered the mist were killed, driven mad, or worse
Only a few Havens keep up the fight against the hordes of bloodthirsty monsters that come out at night from this damned mist. A few strained heroes protect the walls night after night, until a handful of mages manage to cast The Last Spell and banish all magic from this accursed world. And maybe save us all. Maybe.
How to Correctly Write a Raw Multiline String in Python: Essential Tips
5/5 – (1 vote)
Python provides an effective way of handling multiline strings, which you might have encountered when working with lengthy text or dealing with code that spans multiple lines. Understanding how to correctly write a raw multiline string in Python can be essential for maintaining well-structured and easily readable code.
Ordinarily, we express strings in Python using single or double quotes.
However, when it comes to multiline strings, Python offers a special syntax for defining these types of text. To create a multiline string, you can use triple quotes, either single or double, at the beginning and end of your string.
To correctly write a raw multiline string in Python, use the letter “r” before your opening triple quotes while enclosing your string with triple quotes. For example: r'''This is a raw\n Multiline String'''.
This denotes a raw string and preserves special characters such as backslashes (used for escape sequences) without interpreting them as part of the string. Doing so lets you easily and efficiently handle long strings spanning multiple lines in your Python code.
Understanding Raw Strings
In Python, raw strings are a convenient way to represent strings literally, without processing escape characters. This can be particularly useful when working with regular expressions or dealing with file system paths. To create a raw string, simply prefix the string literal with an r or R character.
For example, a regular string containing a backslash (such as in a file path) would need to be escaped:
normal_string = 'C:\\Users\\John\\Documents'
With raw strings, you don’t need to escape the backslashes:
raw_string = r'C:\Users\John\Documents'
Both of these variables will hold the same string value.
When it comes to creating raw multiline strings, you can use triple quotes """ or ''' combined with the raw string prefix to achieve the desired result. Here’s an example:
raw_multiline_string = r"""This is a
raw multiline string
with backslashes \t and \n
that are not escaped."""
This string will preserve the backslashes and newlines as they appear between the triple quotes.
It is important to note that raw strings cannot end with an odd number of backslashes, as the final backslash would escape the final quote character:
# This will raise a SyntaxError
invalid_raw_string = r"This is not valid\"
To deal with this limitation, you can concatenate a regular string with the final backslash:
valid_raw_string = r"This is valid" + "\\"
Multiline Strings
In Python, multiline strings are created using triple quotes, either three single quotes (''') or three double quotes ("""). This allows you to include quotes, tabs, and newlines within the string without using escape characters. Here is an example of a multiline string:
multiline_string = """This is a
multiline string in Python
with newlines, tabs, and "quotes"."""
If you want to create a raw multiline string, you’ll need to use a different approach, as the r prefix only works for single-line strings. One way to achieve this is by combining raw strings and parentheses, adding an r prefix to each part of the string. This will preserve the string’s escape characters:
raw_multiline_string = (r"on\e" r"\\tw\\o")
Keep in mind that when using parentheses, the line break will not be included in the string. You can manually add a line break using the \n escape character in the appropriate location like this:
This method allows you to create raw multiline strings while preserving the escape characters and maintaining readability in your Python code.
Remember: it’s essential to use the r prefix for each part of the string to ensure it’s treated as a raw string. For more information, check out the discussion on Stack Overflow.
3 Ways to Combine Raw and Multiline Strings
In Python, you can combine raw and multiline strings to create a string that spans across multiple lines, while also preserving special characters and escape sequences. This section will explain different ways to achieve this combination.
One common approach is to use triple quotes for creating a multiline string. By using three single quotes (''') or three double quotes ("""), you can create a multiline string that retains any whitespace and can include special characters. To add a raw string, use the r prefix before the triple quotes:
raw_multiline_string = r"""This is a raw
multiline string with a backslash: \\
and a new line \n is just character literals."""
Another way to write a raw multiline string is by using parentheses and string concatenation. Each line of the string can be enclosed in single or double quotes, followed by a space to ensure a single whitespace character divides them. Add the r prefix before each quoted line to maintain the raw string format:
raw_multiline_string = (r"This is a raw" r" multiline string with a backslash: \\" r" and a new line \n is just character literals.")
Alternatively, you can use the + operator to concatenate multiple raw strings, creating a multiline string. This approach allows you to explicitly specify newline characters or other special characters as needed:
raw_multiline_string = (r"This is a raw" + "\n" r" multiline string with a backslash: \\" + "\n" r" and a new line \n is just character literals.")
With these techniques, you can create raw multiline strings that are easier to read and maintain in your Python code.
Multiline Raw String Use Cases and Examples
This section reviews some use cases and examples demonstrating how to correctly write a raw multiline string in Python.
Using raw multiline strings is beneficial when dealing with strings containing many backslashes or with regular expressions. In these scenarios, raw strings prevent the need to escape backslashes, making the code more readable.
Here’s a basic example of creating a raw multiline string:
multiline_raw_string = r"""This is a raw \
multiline string in Python. \\
You don't need to escape the backslashes \\."""
In this example, the backslashes are preserved in the text as they’re written, without the need to escape them, thanks to the r prefix before the triple quotes.
Suppose you want to match a file path pattern in a text, using a regular expression. Without raw strings, you’d need to escape the backslashes:
import re pattern = 'C:\\\\Users\\\\[A-Za-z0-9]+\\\\Documents'
text = 'C:\\Users\\JohnDoe\\Documents\\example.txt' result = re.search(pattern, text)
print(result.group())
With raw strings, the regex pattern becomes more readable, as you don’t need to escape the backslashes:
import re pattern = r'C:\\Users\\[A-Za-z0-9]+\\Documents'
text = 'C:\\Users\\JohnDoe\\Documents\\example.txt' result = re.search(pattern, text)
print(result.group())
In both examples, the output is the same:
C:\Users\JohnDoe\Documents
These examples demonstrate the benefits of using raw multiline strings in Python, especially when working with text that contains special characters like backslashes or incorporating regular expressions in your code.
Feel free to check out our full guide on raw strings here:
You are a border police inspector in a communist country of the early 1980s. Every second driver is a smuggler and the vehicles are stuffed with hidden contraband. Documents, vehicles, cargo.. everything is a subject to detailed control...
How I Created a Machine Learning Web Application Using Django
5/5 – (1 vote)
Deploying a Machine Learning model as a web application makes it easy for others with little or no programming experience to use it.
In previous tutorials, where I explained how I created a house price prediction app and a loan eligibility app, we made use of Streamlit. Streamlit is easy to use. This is why it is a popular choice for data scientists.
In a world where learning one framework isn’t enough, won’t it be nice to learn how to accomplish this using Django?
Understandably, Django can be tough for beginners. The only remedy though is constant practice. If you have been going through some of my tutorials on Django, there is no doubt that you have become familiar with the process.
Therefore, in this tutorial, we will add to your knowledge by creating a machine learning application using Django. Guess what we will used for prediction? The famous Titanic dataset!
Developing Machine Learning Model
The Machine Learning classification problem aims to predict the survival of the passengers based on their attributes. There are multiple steps involved in creating a Machine Learning model. To keep things simple, we will skip those steps and focus on showing how to implement Machine Learning in Django.
Create a folder for this project. Then, inside the folder, create a file named model.py. This is where we will develop our model. You can download the dataset on my GitHub page.
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
import pickle df = pd.read_csv('titanic.csv', index_col=0) # selecting the features we need
df = df[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', 'Survived']] # encoding the column to a numberic value
df['Sex'] = df['Sex'].map({'male': 0, 'female': 1}) # converting the Age column to numberic type
df['Age'] = pd.to_numeric(df.Age) # filling the null values
df['Age'] = df.Age.fillna(np.mean(df.Age)) # creating additional features from Embarked columns after converting to dummy variables
dummies = pd.get_dummies(df.Embarked)
df = pd.concat([df, dummies], axis=1)
df.drop(['Embarked'], axis=1, inplace=True) X = df.drop(['Survived'], axis=1)
y = df['Survived'] # scaling the features
scaler = MinMaxScaler(feature_range=(0,1))
X_scaled = scaler.fit_transform(X) model = LogisticRegression(C=1)
model.fit(X_scaled, y) # saving model as a pickle
pickle.dump(model, open('titanic.pkl', 'wb'))
pickle.dump(scaler, open('scaler.pkl', 'wb'))
After importing the CSV file, we saw that there are missing values in the features selected. We simply fill them up with the mean of the values. We convert the Embarked column to a dummy variable. Then, we add them to the features.
We are using LogisticRegression as the Machine Learning algorithm to make this prediction. Finally, we save the model as a pickle object to be used later.
Creating Django Project
As covered in previous tutorials, the steps to set up a new Django project are as follows:
The (venv) indicates that you are in the virtual environment. Don’t forget to include the dot which signifies creating the project in the current directory. You will see the image below if everything was installed successfully.
Open the settings.py file to let Django know that a new app is created. We will do so in the INSTALLED_APP section.
Let’s configure the URLs for our website. Open the urls.py in the project folder and make it appear like this:
from django.contrib import admin
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('titanic.urls')),
]
Let’s now configure the URLs for the app. Create a urls.py in the app folder.
from django.urls import path
from .views import home, result urlpatterns = [ path('', home, name='home'), path('result/', result, name='result'),
]
Let’s create another file in the app folder named predict.py. This is where we will use the pickled files to make predictions.
import pickle def getPrediction(pclass, sex, age, sibsp, parch, fare, C, Q, S): model = pickle.load(open('titanic.pkl', 'rb')) scaled = pickle.load(open('scaler.pkl', 'rb')) transform = scaled.transform([[pclass, sex, age, sibsp, parch, fare, C, Q, S]]) prediction = model.predict(transform) return 'Not Survived' if prediction == 0 else 'Survived' if prediction == 1 else 'error'
The function contains the exact number of features used to train the model.
Notice we first transform the values the user will input on the web page. Since the trained model was transformed, we have to do the same to any values the user enters. Finally, we return the results based on the prediction.
Alright, let’s head over to the views.py file in the app folder.
from django.shortcuts import render
from .prediction import getPrediction # Create your views here.
def home(request): return render(request, 'home.html') def result(request): pclass = int(request.GET['pclass']) sex = int(request.GET['sex']) age = int(request.GET['age']) sibsp = int(request.GET['sibsp']) parch = int(request.GET['parch']) fare = int(request.GET['fare']) embC = int(request.GET['embC']) embQ = int(request.GET['embQ']) embS = int(request.GET['embS']) result = getPrediction(pclass, sex, age, sibsp, parch, fare, embC, embQ, embS) return render(request, 'result.html', {'result': result})
The home() function simply renders the home.html which contains the form where our users will input some details. Then the result() function will get those details, make predictions, and renders the prediction result.
Notice that we made sure every detail corresponds to the features used in training the model.
The final step is templates. Create a folder bearing the name. Make sure you are doing so in the current directory. Then register it in the settings.py file.
This syntax "{% url 'result' %}" is Django templating language. It’s a link to the result.html. Remember the name argument in the path() function in urls.py? That is another way to refer to the result.html URL. The csrf_token is for security reasons. It’s mandatory when a form is created.
Can you now see it’s from this form we get those names in the result() function? It is here that the data will be collected and sent to the result() function which processes the data, makes predictions, and displays the result in the result.html.
We now create the result.html file in the templates folder.
It’s very simple. The {{ result }} is a variable that will be rendered to this web page. Go back to your result() function to recall if you have forgotten.
That’s it. We are done. Thanks for staying with me so far in this tutorial. Let’s check what we have done. Run the local server.
That is the home page. Everything in the form is displayed. Enter details and make predictions. Remember, only numbers will be in the form. If you are lost, check the dataset using Pandas.
If you encounter an error saying, “No such file or directory: 'titanic.pkl'”, you may have to manually run the model.py to generate the file.
Congratulations!! You are not only a data scientist but also a Django developer.
In this tutorial, we performed Machine Learning using Logistic Regression.
We demonstrated how to implement it using Django.
Exercise: As an assignment, can you use what you have learned to make predictions on the iris dataset, the hello world of data science? Give it a try using Django.
Atelier Ryza 3: Alchemist of the End & the Secret Key
Ryza and her friends are living their lives on Kurken Island when news of a sudden appearance of a mysterious group of islands in nearby waters arrives.
To find a way to save her island, Ryza and her friends will set off on final adventure surrounding the "roots of alchemy."
Reunite with characters from previous games, and meet new characters who will be key to the story. Mix and match your favorite members and enjoy the adventure!