Posted on Leave a comment

The Fasting Cure [Book Summary + Free Download]

5/5 – (1 vote)

Fasting has many scientifically proven benefits for your body and overall health:

Intermittent fasting improved blood pressure and resting heart rates as well as other heart-related measurements. Physical performance. Young men who fasted for 16 hours showed fat loss while maintaining muscle mass. Mice who were fed on alternate days showed better endurance in running.Johns Hopkins Medicine

While Finxter is not a health blog and I am not a medical advisor, allow me to share this age-old wisdom from the book “The Fasting Cure” by Upton Sinclair.

Intermittent fasting has helped me and many other highly productive individuals create more value, stay more healthy, and maximize their productivity — in coding, business, or any other professional field.

💰 Fasting can make you more money—so keep reading!

This short book summary is based on the original book that can be downloaded for free here. I’ll give many direct quotes from the book but only the ones that I think are useful for you so you don’t have to read the whole book by yourself. All highlights are my own.

Perfect Health

The Fasting Cure appeared in Cosmopolitan Magazine in the year 1910—you see: few things are as well-researched and well-understood as the benefits of fasting. More than 100 years later and scientists still agree on the benefits of fasting!

Like nobody would argue against the benefits of sleep, nobody can argue with the benefits of fasting.

Let that sink in. 🪨

The book starts with a strong opening paragraph about Perfect Health:

Have you any conception of what the phrase means? Can you form any image of what would be your feeling if every organ in your body were functioning perfectly? Perhaps you can go back to some day in your youth, when you got up early in the morning and went for a walk, and the spirit of the sunrise got into your blood, and you walked faster, and took deep breaths, and laughed aloud for the sheer happiness of being alive in such a world of beauty. And now you are grown older—and what would you give for the secret of that glorious feeling? What would you say if you were told that you could bring it back and keep it, not only for mornings, but for afternoons and evenings, and not as something accidental and mysterious, but as something which you yourself have created, and of which you are completely master? (source)

Everybody wants to be healthy, full of energy, and free from pain. Being healthy means not only a much better quality of life, but health is also the source of all human productivity.

The more you lose health, the less you get done. So spend some time on your health daily!

It is simply that for ten years I have been studying the ill health of myself and of the men and women around me. And I have found the cause and the remedy. I have not only found good health, but perfect health; I have found a new state of being, a new potentiality of life; a sense of lightness and cleanness and joyfulness, such as I did not know could exist in the human body. (source)

Next, the book goes into some personal stories of the health struggles of the author, while interesting, we’ll skip over them quickly—time is scarce.

Here’s the kicker story that made the author act on the fasting cure:

So matters stood when I chanced to meet a lady, whose radiant complexion and extraordinary health were a matter of remark to everyone. I was surprised to hear that for ten or fifteen years, and until quite recently, she had been a bed-ridden invalid. She had lived the lonely existence of a pioneer’s wife, and had raised a family under conditions of shocking ill-health. She had suffered from sciatica and acute rheumatism; from a chronic intestinal trouble which the doctors called “intermittent peritonitis”; from intense nervous weakness, melancholy, and chronic catarrh, causing deafness. […] And this woman, when she took the ride, had not eaten a particle of food for four days previously! […] That was the clue to her escape: she had cured herself by a fast. She had abstained from food for eight days, and all her troubles had fallen from her. Afterwards she had taken her eldest son, a senior at Stanford, and another friend of his, and fasted twelve days with them, and cured them of nervous dyspepsia. And then she had taken a woman friend, the wife of a Stanford professor, and cured her of rheumatism by a week’s fast. I had heard of the fasting cure, but this was the first time I had met with it. […] After another spell of hard work I found myself unable to digest corn-meal mush and milk; and so I was ready for a fast. (source)

Next, the author describes how he implemented his first fasting streak and how it helped him resolve his limitations of certain types of foods:

I had not taken what is called a “complete” fast—that is, I had not waited until hunger returned. Therefore I began again. I intended only a short fast, but I found that hunger ceased again, and, much to my surprise, I had none of the former weakness. I took a cold bath and a vigorous rub twice a day; I walked four miles every morning, and did light gymnasium work, and with nothing save a slight tendency to chilliness to let me know that I was fasting. I lost nine pounds in eight days, and then went for a week longer on oranges and figs, and made up most of the weight on these.

I shall always remember with amusement the anxious caution with which I now began to taste the various foods which before had caused me trouble. Bananas, acid fruits, peanut butter—I tried them one by one, and then in combination, and so realized with a thrill of exultation that every trace of my old trouble was gone. (source)

Let’s dive into some of the benefits of fasting and learn a couple of more insights into its working. Don’t forget that this was already figured out more than one hundred years ago!

The fast is to me the key to eternal youth, the secret of perfect and permanent health. I would not take anything in all the world for my knowledge of it. It is Nature’s safety-valve, an automatic protection against disease. I do not venture to assert that I am proof against virulent diseases, such as smallpox or typhoid. I know one ardent physical culturist, a physician, who takes typhoid germs at intervals in order to prove his immunity, but I should not care to go that far; it is enough for me to know that I am proof against all the common infections which plague us, and against all the “chronic” troubles. And I shall continue so just as long as I stand by my present resolve, which is to fast at the slightest hint of any symptom of ill-being—a cold or a headache, a feeling of depression, or a coated tongue, or a scratch on the finger which does not heal quickly.

Those who have made a study of the fast explain its miracles in the following way: Superfluous nutriment is taken into the system and ferments, and the body is filled with a greater quantity of poisonous matter than the organs of elimination can handle. The result is the clogging of these organs and of the blood-vessels—such is the meaning of headaches and rheumatism, arteriosclerosis, paralysis, apoplexy, Bright’s disease, cirrhosis, etc. And by impairing the blood and lowering the vitality, this same condition prepares the system for infection—for “colds,” or pneumonia, or tuberculosis, or any of the fevers. As soon as the fast begins, and the first hunger has been withstood, the secretions cease, and the whole assimilative system, which takes so much of the energies of the body, goes out of business. The body then begins a sort of house-cleaning, which must be helped by an enema and a bath daily, and, above all, by copious water-drinking. The tongue becomes coated, the breath and the perspiration offensive; and this continues until the diseased matter has been entirely cast out, when the tongue clears and hunger reasserts itself in unmistakable form.

Fasting and Weight

Now, you may ask: Can fasting help you lose weight?

Strange as it may seem, the fast is a cure for both emaciation and obesity. After a complete fast the body will come to its ideal weight. People who are very stout will not regain their weight; while people who are under weight may gain a pound or more a day for a month.

So fasting will help you reach your ideal weight, according to the author.

Next, he goes on with some more anecdotal material on how fasting has helped his wife and friends and thousands of readers who wrote in—the author became quite a celebrity on the subject of health and fasting. Fascinating!

While I skipped most of the anecdotes, I believe this excerpt from the book summarizes his enthusiasm quite well:

The reader may think that my enthusiasm over the fasting cure is due to my imaginative temperament; I can only say that I have never yet met a person who has given the fast a fair trial who does not describe his experience in the same way. I have never heard of any harm resulting from it, save only in cases of tuberculosis, in which I have been told by one physician that people have lost weight and not regained it.

I regard the fast as Nature’s own remedy for all other diseases. It is the only remedy which is based upon an understanding of the fundamental nature of disease. And I believe that when the glad tidings of its miracles have reached the people it will lead to the throwing of 90 per cent of our present materia medica into the waste-basket. This may be unwelcome to those physicians who are more concerned with their own income than they are with the health of their patients; but I personally have never met any such physicians, and so I most earnestly urge it upon medical men to investigate the extraordinary and almost incredible facts about the fasting cure.

Next, he goes over several anecdotes where readers of the author’s articles sent in some of their own positive experiences with fasting and how it helped them solve their health issues.

Even other medical doctors wrote in sharing their own supportive evidence of the benefits of fasting as observed in their own medical practices.

Water and Milk

While I don’t want to discuss possibly outdated implementation tactics on fasting — such as drinking lots of milk while doing it — here’s one that you cannot argue with:

One should drink all the water he possibly can while fasting, only not taking too much at a time. I take a glass full every hour, at least; sometimes every half hour.

And speaking of the suggested milk diet, the author did have mixed evidence of its benefits:

Also I tried on many occasions to take the milk diet after a short fast of three or four days, and always the milk has disagreed with me and poisoned me.

I take it as evidence that the concrete implementation of the fasting diet must be well-researched and you should read the latest research on it.

Fasting and Disease

Anyways, most implementations of fasting seems to be beneficial for your body’s long-term and sustainable well-being.

People ask me in what diseases I recommend fasting. I recommend it for all diseases of which I have ever heard, with the exception of one in which I have heard of bad results—tuberculosis.

The latter not being an issue in many parts of the developed world anymore (fortunately).

The diseases for which fasting is mos obviously to be recommended are all those of the stomach and intestines, which any one can see are directly caused by the presence of fermenting and putrefying food in the system. Next come all those complaints which are caused by the poisons derived from these foods in the blood and the eliminative organs: such are headaches and rheumatism, liver and kidney troubles, and of course all skin diseases. Finally, there are the fevers and infectious diseases, which are caused by the invasion of the organism by foreign bacteria, which are enabled to secure a lodgment because of the weakened and impure condition of the blood-stream. Such are the “colds” and fevers. In these latter cases nature tries to save us, for there is immediately experienced a disinclination on the part of the sick person to take any sort of food; and there is no telling how many people have been hurried out of life in a few days or hours, because ignorant relatives, nurses and physicians have gathered at their bedside and implored them to eat.

To summarize, this is the author’s view on the question: when is the best time to start fasting?

The fast is Nature’s remedy for all diseases, and there are few exceptions to the rule. When you feel sick, fast. Do not wait until the next day, when you will feel stronger, nor till the next week, when you are going away into the country, but stop eating at once.

Fasting as a Wage Slave

Can you fast if you are a “wage slave”, i.e., you work as an employee for an hourly or monthly rate, and you cannot stop?

  • First, consider breaking free (e.g., by becoming a freelance developer working from home on their own business).
  • Second, consider that you can still do fasting:

Many of the people who wrote to me were victims of our system of wage slavery, who wrote me that they were ill, but could not get even a few days’ release in which to fast. They wanted to know if they could fast and at the same time continue their work. Many can do this, especially if the work is of a clerical or routine sort. On my first fast I could not have done any work, because I was too weak. But on my second fast I could have done anything except very severe physical labor. I have one friend who fasted eight days for the first time, and who did all her own housework and put up several gallons of preserves on the last day. I have received letters from a couple of women who have fasted ten or twelve days, and have done all their own work. I know of one case of a young girl who fasted thirty-three days and worked all the time at a sanatorium, and on the twenty-fourth day she walked twenty miles.

Fasting Study on Small Data

Next, a very interesting “Symposium on fasting” presents the results of a questionnaire with 277 data points — not much in today’s age of research and big data.

So, I give only the quick list of diseases benefited from the fasting cure, according to the small study (take it with a grain of salt):

Following is the complete list of diseases benefited—45 of the cases having been diagnosed by physicians: indigestion (usually associated with nervousness), 27; rheumatism, 5; colds, 8; tuberculosis, 4; constipation, 14; poor circulation, 3; headaches, 5; anæmia, 3; scrofula, 1; bronchial trouble, 5; syphilis, 1; liver trouble, 5; general debility, 5; chills and fever, 1; blood poisoning, 1; ulcerated leg, 1; neurasthenia, 6; locomotor ataxia, 1; sciatica, 1; asthma, 2; excess of uric acid, 1; epilepsy, 1; pleurisy, 1; impaction of bowels, 1; eczema, 2; catarrh, 6; appendicitis, 3; valvular disease of heart, 1; insomnia, 1; gas poisoning, 1; grippe, 1; cancer, 1.

The Ideal Fasting Diet

But what is the ideal fasting diet? The author goes on to discuss this exact question.

The general rules are mostly of a negative sort. There are many kinds of foods, some of them most generally favored, of which one may say that they should never be used, and that those who use them can never be as well as they would be without them. Such foods are all that contain alcohol or vinegar; all that contain cane sugar; all that contain white flour in any one of its thousand alluring forms of bread, crackers, pie, cake, and puddings; and all foods that have been fried—by which I mean cooked with grease, whether that grease be lard, or butter, or eggs or milk. It is my conviction that one should bar these things at the outset, and admit of no exceptions. I do not mean to say that healthy men and women cannot eat such things and be well; but I say that they cannot be as well as they would be without them; and that every particle of such food they eat renders them more liable to all sorts of infection, and sows in their systems the seeds of the particular chronic disease that is to lay them low sooner or later.

A perfectly normal and well person is, under the artificial conditions of our bringing up, a very great rarity; and so we all have to regard ourselves as more or less diseased, and work towards the ideal of soundness. We must do this with intelligence—there is no short cut, no way to save one’s self the trouble of thinking.

Eating Fruits

Okay, and now here’s my own gold standard of a healthy diet: mainly fresh fruits. 🍌🍎🍓🫐

That’s super cheap, and it just has to be super healthy:

By way of setting an ideal, let me give you the example of a young lady who for six or seven months has been living in our home, and giving us a chance to observe her dietetic habits. This young lady three years ago was an anæmic school-teacher, threatened with consumption, and a victim of continual colds and headaches; miserable and beaten, with an exopthalmic goitre which was slowly choking her to death. She fasted eight days, and achieved a perfect cure. She is to-day bright, alert and athletic; and she lives on about twelve hundred calories of food a day—one half what I eat, and less than a third of the old-school dietetic standards. Occasionally she will eat nut butter, or sweet potato, or some whole wheat crackers with butter, or a dish of ice-cream; but at least ninety per cent of her food has consisted of fresh fruit. Meal after meal, day after day, I have seen her eat one or two bananas and two or three peaches, or say, a slice of watermelon or canteloupe; at some meals she will eat only the peaches, and then again she will eat nothing. A dollar a week would pay for all her food; and on this diet she laughs and talks, reads and thinks, walks and swims with my wife and myself—a kind of external dietetic conscience, which we would find it hard to get along without. And tell me, Dr. Woods Hutchinson, or other scoffer at the “food-faddists,” don’t you think that a case like this gives us some right to ask for patient investigation of our claims? Or will you stand by your pill boxes and your carving-knives and the rest of your paraphernalia, and compel us to cure all your patients in spite of you?

Speaking of fruits, let’s see what the book tells us about meat:

Eating Meat

I am asked many questions as to my attitude toward the question of meat-eating. I was brought up on a diet of meat, bread and butter, potatoes, and sweet things. Four years ago when I found myself desperately run down, suffering from nervousness, insomnia, and almost incessant headaches, I came upon various articles written by vegetarians, and I began to suspect that my trouble might be due to meat. I went away on a camping-trip for several weeks, taking no meat with me, and because I found that I was a great deal better, I believed that the meat had been responsible for my trouble. I then visited the Battle Creek Sanitarium, and became familiar with all their arguments against meat, and thereafter I did not use it for three years. I called myself a vegetarian; but at the same time I realized that I differed from most vegetarians in some important particulars.

Well, nothing surprising here. Vegetarians were much more uncommon back in the old days. But now we know without a shadow of a doubt that vegatarians are healthier and live longer. It has been proven by many studies that a vegetarian diet is much healthier:

In most countries, vegetarian diets were associated with a lower intake of energy and saturated fat, and a better cardiovascular profile (lower body weight, LDL cholesterol levels, blood pressure, fasting glucose, and triglycerides)Hargreaves et al. International Journal Environ Res Public Health

Here’s an interesting take from the book on contamination of meat:

There have been numerous expositions of the greater liability of meat to contamination. Dr. Kellogg, for instance, has purchased specimens of meat in the butcher-shops, and has had them examined under the microscope, and has told us how many hundreds of millions of bacteria to the gram have been discovered. This argument has a tendency to appal one; I know it had great effect upon me for a long time, and I took elaborate pains to take into my system only those kinds of food which were sterilized, or practically so. This is the health regimen which is advocated by Professor Metchnikoff; one should eat only foods which have been thoroughly boiled and sterilized. I have come, in the course of time, to the conclusion that this way of living is suicidal, and that there is no way of destroying one’s health more quickly. I think that the important question is, not how many bacteria there are in the food when you swallow it, but how many bacteria there come to be in food after it gets into your alimentary canal. The digestive juices are apparently able to take care of a very great number of germs; it is after the food has passed on down, and is lodged in the large intestine, that the real fermentation and putrefaction begin—and these count for more, in the question of health, than that which goes on in the butcher-shop or the refrigerator or the pantry

Is meat good for physical labor jobs?

I have been accustomed all my life to think of meat as a very “heavy” article of food, an article of food suited for men doing hard physical labor; it is a curious fact that the view I am setting forth here is precisely the opposite. So long as I am doing hard physical labor, whether it is walking ten miles a day, or playing tennis, or building a house, I get along perfectly upon the raw food; but when I settle down for long periods of thinking and writing—often sitting for six hours without moving from one position—I find that I need something else, and nothing has answered that purpose quite so well as beef-steak. It appears to be, so far as I am concerned, the most easily digested and most easily assimilated of foods. And because the work that I am doing seems to me to be important, I am willing to make the sacrifice of money and time and trouble which it necessitates. My diet at such times will consist of beef or chicken, shredded wheat biscuit, and a little fruit. If any one is disposed to follow my example and make this experiment, I beg to call his attention especially to the fact that I name these three kinds of food, and none others; and that I mean these three kinds and none others. The main trouble with advising anybody to eat meat is that he proceeds to eat it in the everyday world, where it means not the eating of broiled lean beef, but also of bacon and eggs, and of bread and butter, and of potatoes with cream gravy, and of rice pudding and crackers and cheese and coffee. Please do not proceed to eat these things and then hold meat-eating responsible for the consequences.

The book ends with a couple of articles and testimonials submitted by avid readers of the author. I think we can skip those safely because they are mostly anecdotical.

Fasting – Conclusion, Benefits, and How to Start

Let’s finish up this book summary about the fasting diet with the top benefits of fasting as reported by Healthline:

  • Promotes Blood Sugar Control by Reducing Insulin Resistance
  • Promotes Better Health by Fighting Inflammation
  • May Enhance Heart Health by Improving Blood Pressure, Triglycerides and Cholesterol Levels
  • May Boost Brain Function and Prevent Neurodegenerative Disorders
  • Aids Weight Loss by Limiting Calorie Intake and Boosting Metabolism
  • Increases Growth Hormone Secretion, Which Is Vital for Growth, Metabolism, Weight Loss and Muscle Strength
  • Could Delay Aging and Extend Longevity
  • May Aid in Cancer Prevention and Increase the Effectiveness of Chemotherapy

All of those are backed by science (see article referenced). The article also points out the most common ways to start fasting:

  • Water fasting: Drinking only water
  • Juice fasting: Drinking vegetable or or fruit juice
  • Intermittent fasting: Limit your fasting period to a number of hours daily (e.g., 16 hours non-eating per day)
  • Partial fasting: Eliminate certain foods such as processed foods or sugar or alcoholic beverages.
  • Calorie restriction: Just eat fewer calories for a fixed time.

I personally prefer intermittent fasting as it can be integrated easily into your daily life and still has many of the benefits.


Posted on Leave a comment

How to Strip One Set of Double Quotes from Strings in Python

5/5 – (1 vote)

Problem Formulation and Solution Overview

When working with data, you may encounter a string or list of strings containing two (2) double quotes. This article shows you how to remove one set of these double quotes.


💬 Question: How would we write code to remove the extra set of double quotes?

We can accomplish this task by one of the following options:


Method 1: Use startswith() and endswith()

This method uses startswith() and endswith() in conjunction with slicing to remove one set of double quotes from a string.

web_name = '""The Finxter Acadcemy""' if web_name.startswith('"') and web_name.endswith('"'): web_name = web_name[1:-1]
print(web_name)

The first line in the above code snippet declares a string containing two (2) sets of double quotes and saves this to the variable web_name.

The following line calls the if statement with the startswith() and endswith() functions. Both functions are passed the argument ('"').

This statement checks to see if web_name starts with and ends with the above argument. If true, the code moves to the next line and, using slicing, removes the specified character.

The results are output to the terminal.

"The Finxter Acadcemy"
YouTube Video

Method 2: Use Regex

You can use the regex method re.sub() to remove one set of double quotes from a string.

import re msg = '""Boost Your Python Skills""'
msg = re.sub(r'^"|"$', '', msg)
print(msg )

The first line in the above code snippet imports the re library. This allows access to and manipulation of strings to extract the desired result.

The following line declares a string containing two (2) sets of double quotes and saves this to the variable msg.

The next line uses re.sub() to search this string for any occurrences of double quotes, removes the same and saves the result back to msg. This overwrites the original string.

The results are output to the terminal.

"Boost Your Python Skills"

Another option is to use re.sub() and pass this function two (2) arguments:

  • the string to replace and
  • the string to replace it with.
msg = '""Boost Your Python Skills""'
msg = re.sub('""', '"', msg)
print(msg)
"Boost Your Python Skills"
YouTube Video

Method 3: Use replace()

This method uses replace() to remove one set of double quotes from a string.

mission = '""Boost Collective Intelligence""'
mission = mission.replace('""', '"')
print(mission) 

The first line in the above code snippet declares a string containing two (2) sets of double quotes and saves this to the variable mission.

The following appends the replace() function to mission and is passed two (2) arguments:

  • the string to replace, and
  • the string to replace it with.

The results save back to mission. The results are output to the terminal.

"Boost Collective Intelligence"

Method 4: Use list()

This method passes a list containing double quotes to the list function. This option differs from the other options as it removes all double quotes.

user_emails = [""'alice@acme.ca', 'doug@acme.ca', 'fran@acme.ca', 'stan@acme.ca'""]
user_emails = list(user_emails)
print(user_emails)

The first line in the above code contains a list of Finxter user’s emails with double quotes at the beginning and the end.

This saves to user_emails.

The following line uses a list and passes user_emails to it as an argument. The results save back to user_emails and are output to the terminal.

['alice@acme.ca', 'doug@acme.ca', 'fran@acme.ca', 'stan@acme.ca']

💡Note: Converting a list containing double quotes to a list removes all double quotes.

YouTube Video

Method 5: Use Pandas

This method uses Pandas to remove all double quotes from a CSV file.

Contents of CSV file

Store,Category,Product,Number
""Toronto"",""Jeans"",""10534"",""15""
""Montreal"",""Tops"",""5415"",""32""
""Ottawa"",""Coats"",""98341"",""22""
import pandas as pd df = pd.read_csv('quotes.csv',header=None)
df.replace('"', '', inplace=True, regex=True)
print(df)

The above example imports the Pandas library. This library allows access to and manipulation of a Pandas DataFrame.

The following line reads in the CSV file, without the header row into the DataFrame, df.

If output to the terminal, the DataFrame appears as follows:

0 1 2 3
0 Shop Category Product Number
1 Toronto”” Jeans”” 10534″” 15″”
2 Montreal”” Tops”” 5415″” 32″”
3 Ottawa”” Coats”” 98341″” 22″”

💡Note: By default, when the CSV file was imported, the beginning double quotes were removed, thus leaving the trailing double quotes.

Next, all occurrences of trailing quotes are replaced (removed) from the DataFrame.

The output of the modified DataFrame, df are output to the terminal.

0 1 2 3
0 Shop Category Product Number
1 Toronto Jeans 10534 15
2 Montreal Tops 5415 32
3 Ottawa Coats 98341 22
YouTube Video

Summary

This article has provided five (5) ways to remove one set of double quotes from a string and all double quotes to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd
Posted on Leave a comment

Python Create JSON File

5/5 – (1 vote)

Problem Formulation and Solution Overview

This article focuses on working with a JSON file. JSON is an acronym for JavaScript Object Notation. This is a flat-text file formatted based on JavaScript (JS) Syntax.

This file is most commonly noted for its ability to transmit data to/from web applications, such as sending/receiving data from a Server/Client to display or retrieve said data.

The JSON file structure has keys and values similar to a Python Dictionary.

This structure can contain strings, boolean, integers, floats, lists, and much more. This file structure can be as simple or complex as needed.

This article works with Rivers Clothing, a new start-up. They have hired their first three (3) employees. This employee data is displayed as a List of Dictionaries.

emps = {"hires": [{"ID": 324, "name": "Alex Smith", "title": "Manager"}, {"ID": 325, "name": "Micah Jones", "title": "Designer"}, {"ID": 326, "name": "Sam Quinn", "title": "Coder"}]}

💬 Question: How would we write code to create and work with a JSON File?

  1. Python Create JSON File if Not Exists
  2. Python Create JSON String from List of Dictionaries
  3. Python Create JSON File and Write Data
  4. Python Read JSON File
  5. Python Access JSON Elements
  6. Python Delete JSON Elements

Python Create JSON File if Not Exists

This example creates an empty JSON file if one does not exist in the current working directory.

import os filename = 'employees.json'
isFile = os.path.isfile(filename) if (not isFile): with open(filename, 'w') as fp: pass
else: print(f'The {filename} file exists.')

The first line in the above code snippet imports Python’s built-in os library. This allows access to and manipulation of files and folders.

The following line declares the JSON file name, employees.json and saves it to the variable filename.

The next line calls the os.path.isfile() function and passes it one (1) argument, filename. This function checks the current directory for the existence of the employees.json file

The first time this code runs, and this file is not found (isFile is False), an empty file is created and placed into the current working directory.

💡Note: The pass statement is a placeholder code and does nothing when executed. This is used here so a file is created, and nothing else occurs.

If this code is rerun or the file exists, the following message is output to the terminal.

The employees.json file exists.

To create this file in a sub-folder, you would modify the code as follows:

import os filename = 'files\\employees.json'
isFile = os.path.isfile(filename) if (not isFile): with open(filename, 'w') as fp: pass
else: print(f'The {filename} file exists.')

When this code runs, the files folder is checked for the existence of the employees.json file.

YouTube Video

Python Create JSON String from List of Dictionaries

This example creates a JSON string from a List of Dictionaries.

import json emps = {"hires" :[{"empID": "RC-3243", "name": "Alexa Smith", "title": "Manager"}, {"empID": "RC-3244", "name": "Micah Jones", "title": "Designer"}, {"empID": "RC-3245", "name": "Sam Quinn", "title": "Coder"}]} json_str = json.dumps(emps, indent=4)
print(json_str)

The above code snippet imports the json library. This library allows access to JSON functions.

The following three (3) lines construct a List of Dictionaries containing data for the new hires. The results save to emps.

Next, json.dumps() is called and passed two (2) arguments: a List of Dictionaries, emps, and for formatting, spaces to indent. The results save to json_str and output to the terminal.

{
"hires": [
{
"ID": 3243,
"name": "Alexa Smith",
"title": "Manager"
},
{
"ID": 3244,
"name": "Micah Jones",
"title": "Designer"
},
{
"ID": 3245,
"name": "Sam Quinn",
"title": "Coder"
}
]
}

💡Note: The json.dumps() function formats the JSON string. To write this to a file, json.dump() is used.


Python Create JSON File and Write Data

This example writes a List of Dictionaries to a JSON file.

import os
import json filename = 'employees.json'
isFile = os.path.isfile(filename) emps = {"hires" :[{"ID": 3243, "name": "Alexa Smith", "title": "Manager"}, {"ID": 3244, "name": "Micah Jones", "title": "Designer"}, {"ID": 3245, "name": "Sam Quinn", "title": "Coder"}]} if (not isFile): with open(filename, 'w') as fp: json.dump(emps, fp, indent=4)
else: print(f'An error occurred writing to {filename}.') 

The above code snippet adds the two (2) highlighted lines to write the formatted JSON string to the employees.json file.

The contents of this file is as follows:

{
"hires": [
{
"ID": 3243,
"name": "Alexa Smith",
"title": "Manager"
},
{
"ID": 3244,
"name": "Micah Jones",
"title": "Designer"
},
{
"ID": 3245,
"name": "Sam Quinn",
"title": "Coder"
}
]
}

Python Read JSON File

In this example, the JSON file saved earlier is read back in.

import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l print(json_str)

This code snippet opens, reads the employees.json file and saves it to json_str. Upon each iteration, any additional newline (\n) characters are removed using the replace() function.

Once all lines have been read, the contents of json_str is output to the terminal and is the same as indicated above.

YouTube Video

Python Access JSON Elements

This example reads in the previously saved JSON file and accesses the ID element from each hire.

import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l all_emps = json.loads(json_str)
alexa_id = all_emps['hires'][0]['ID']
sam_id = all_emps['hires'][2]['ID']
print(alexa_id, sam_id)

As outlined earlier in this article, the employees.json file is read in, parsed and saved to json_str.

Then, json_str is loaded using json_loads() and passed one (1) argument, the json_str created above. This gives us access to the elements.

The following lines access the Employee IDs for Alexa and Micah and outputs same to the terminal.

3243 3245

To iterate and display the ID and name for each new hire, run the following code:

import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l all_emps = json.loads(json_str) for item in all_emps['hires']: print(item['ID'], item['name'])

Another option is to use List Comprehension to retrieve the data:

results = [item['ID'] for item in all_emps['hires']]
print(results)
YouTube Video

Python Delete Elements

This example reads in the previously saved JSON file and deletes the new hire, Micah Jones.

import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l all_emps = json.loads(json_str)
idx = 0 for item in all_emps['hires']: if idx == 1: del all_emps['hires'][idx] idx += 1
print(all_emps)

Summary

We hope you enjoyed this article about converting a List of Dictionaries to JSON and everything in between!

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd
Posted on Leave a comment

How to Open a URL in Your Browser From a Python Script?

5/5 – (1 vote)

To open a URL in your standard browser (Win, macOS, Linux) from your Python script, e.g., call webbrowser.open('https://google.com') to open Google. Don’t forget to run import webbrowser first. But you don’t have to install the module because it’s already in Python’s standard library.

Example

Here’s an example Python script that opens the URL 'https://finxter.com':

import webbrowser
webbrowser.open('https://finxter.com/')

A new browser tab with your default browser (Chrome, Edge, Safari, Brave — whatever you set up as standard browser in your OS settings) opens, initialized with the URL provided as a string argument of the webbrowser.open() function:

About the Webbrowser Module

The webbrowser module is already part of the Python Standard Library, so you can import it without needing to install it first.

You can also run the module from your command line or terminal by using the following command:

python -m webbrowser -t "https://finxter.com"

Good to know if you ever want to open a URL from your operating system command line or terminal (Windows, macOS, Linux, Ubuntu) because the fact that you use Python makes it portable and operating system independent!

Webbrowser open()

You can specify additional arguments to get more control over which tab is opened by means of the new argument of the webbrowser.open() function.

webbrowser.open(url, new=0, autoraise=True)

The new argument allows you to control the browser window:

  • If you set new=0 (default), you open the URL in the same browser window.
  • If you set new=1, you open a new browser window.
  • If you set new=2, you open a new browser tab.

The autoraise argument allows you to raise the window (default behavior).

Webbrowser Open in New Tab

A short way of opening a given URL in a new tab from your Python script is to call webbrowser.open_new_tab() and pass your URL string as a single argument.

import webbrowser
my_url = 'https://finxter.com'
webbrowser.open_new_tab(my_url)

Select the Webbrowser

You can also return a controller object for a given browser by calling webbrowser.get() and passing the browser type into it. Now, you can call the open() or open_new_tab() methods on this controller object to open the URL in your desired web browser.

import webbrowser
webbrowser.get("chrome").open("https://finxter.com")

Here are the supported browser types:

Type Name Class Name
'mozilla' Mozilla('mozilla')
'firefox' Mozilla('mozilla')
'netscape' Mozilla('netscape')
'galeon' Galeon('galeon')
'epiphany' Galeon('epiphany')
'skipstone' BackgroundBrowser('skipstone')
'kfmclient' Konqueror()
'konqueror' Konqueror()
'kfm' Konqueror()
'mosaic' BackgroundBrowser('mosaic')
'opera' Opera()
'grail' Grail()
'links' GenericBrowser('links')
'elinks' Elinks('elinks')
'lynx' GenericBrowser('lynx')
'w3m' GenericBrowser('w3m')
'windows-default' WindowsDefault
'macosx' MacOSXOSAScript('default')
'safari' MacOSXOSAScript('safari')
'google-chrome' Chrome('google-chrome')
'chrome' Chrome('chrome')
'chromium' Chromium('chromium')
'chromium-browser' Chromium('chromium-browser')

Thanks for Reading ❤

To keep learning, feel free to check out our email academy and download our free Python cheat sheets. 🙂

Posted on Leave a comment

Learn the Basics of MicroPython for Absolute Python Beginners

5/5 – (1 vote)

When learning how to program your Raspberry Pi Pico, you need to learn basic concepts of a limited version of the Python programming language known as MicroPython.

It’s a great way to learn Python, as it is much simpler than Python, which can be very complicated and take a long time to master.

For the purposes of using a microcontroller, you only need to know some basics to get started.

Before we jump in, let’s take a quick moment to familiarize you with your Python IDE, Thonny.

Using Thonny

To get started, there are three parts of the interface that you should be aware of — the toolbar, the editor, and the shell.

(1) Toolbar 🪛

The toolbar has icons that will help you do a few things, such as creating new files, opening existing ones, and saving, just like you see with most programs.

The other things you’ll want to notice are the green button, which will run your programs that you write in the editor and the stop button which will end programs that run forever.

We’ll get into that in the next tutorial.

(2) Editor 📝

The editor is where you will write your programs that you will save and run by using the run button in the toolbar. You may also see or hear this referred to as the script area, as this is where you write your scripts.

(3) Shell ◼

The Python shell has two purposes.

You can run individual instructions by hitting the Enter key without having to write them in the editor and run them, but this only really is good for simple instructions. You won’t use it to write complex code.

The second purpose is to provide information about scripts that you have written, including where errors might be in your code.

This is sometimes referred to as REPL, which stands for

  • Read,
  • Evaluate,
  • Print, and
  • Loop.

In the following tutorial and video, I’ll show you how to get started with the Thonny IDE—feel free to check it out! 👇

🌍 Recommended Tutorial: Getting Started With Thonny – The Optimal IDE for the Raspberry Pi Pico

Writing Your First Code

Ok, so now that you know the parts of the interface, let’s try some code to get started.

We’ll begin with the universal first program, “Hello, World”. First, we’re going to try it in the shell since it’s only a one-line command.

Type the following command like so:

print("Hello, World!")

The results should be that the words "Hello, World!" print in the shell, but without quotation marks.

This is the syntax we use when we want to print something – print(), with whatever you want printed put inside the parentheses. If it’s words, we put them inside quotes.

Now, we’re going to run the program from the editor.

If you want to clear out anything you’ve done in the shell or just start fresh, then click in the shell and press either Command+k on a Mac or Control+k on a PC.

Personally, I like to keep my shell clean and clear when I’m doing something new.

Ok, so now that you’ve cleared the shell (if that’s what you chose to do), type the same command as before into the editor, then click the Save icon.

When prompted to decide where to save the file, choose the Raspberry Pi Pico and title your file "Hello_World.py". Don’t forget to add the ".py" to the end, as this is the file extension that denotes a Python file.

We’ll do that with every file we create with Thonny.

Once you’ve saved, click the green Run button in the toolbar, and you’ll see Hello, World! print in the shell as you did before.

There are two things going on here.

First, you are telling Thonny to print something out in the shell, and second, by using quotation marks, you are telling Thonny that what is to be printed is a string of text.

In programming languages like Python, there are what are known as “primitives”, which are basic data types to work with in your programming.

Those data types are:

  • Strings – just plain ol’ text, like "Hello World"
  • Integers – whole numbers, like 42
  • Floats – numbers with decimals, like 3.14
  • Booleans – choices between two options, like True or False

Loops and Indentation

Now you’re going to write your first loop, which is simply a term that refers to a set of instructions to be repeated.

You will be writing those instructions in a specific type of way. The reason for this is that Python programs run from top to bottom, but your interpreter is dumb.

It only knows what you tell it, so the way we give instructions to the Python interpreter is by grouping those instructions with indentations.

What we’re going to do is tell Thonny to print some text, run a loop, then print more text. When we give the instructions that are to be repeated by the loop, we will indent those instructions so that Thonny will “understand”.

There are two primary loop types, but today, we are only going to focus on what is called a “for loop”, which runs a defined number of times.

First, let’s start a new program by clicking the new file icon (the white piece of paper 📃) then writing some code in the editor like so:

print("Loop starting!")
for i in range(10):

Then hit the Enter (PC) or Return (Mac) key. 

What you’re doing is assigning a variable, i, for the loop to use as a counter and telling it that i will be every number in the range of 10 as the loop is performed.

In other words, the instructions will be repeated 10 times, as defined by the range.

💡 Info: Python is known as a 0-indexed language, which means the default start of the range is 0 rather than 1, so 10 is not included in the range. Therefore, numbers starting with 0 is the range 0-9, so i will be the numbers 0-9 in this example.

The other thing to notice here is the colon : at the end of the line.

That tells Thonny that you are about to give it instructions for the loop you just told it will be performed. When you hit the Enter or Return key, not only will a new line be created, but it will also automatically start at an indented 4 spaces in.

This is where you’re going to tell Thonny what instructions to repeat. For the sake of this exercise, we’re simply going to print to the shell.

However, this time, we’re going to print both a string and whatever number i happens to be for each repetition of the loop.

So to do that, type 

print("Loop number", i)

We need to separate multiple data types being printed on the same line with a comma so that Thonny “knows” that there are separate things to interpret because again, your interpreter only knows what you tell it.

After that, hit Enter or Return for a new line, but this time, hit the backspace key.

We don’t want Thonny to repeat the next instructions, so we need to make sure they are outside of the loop.

Then type 

print("Loop ended!")

Your whole program will look like this:

Here for copy&paste:

print("Loop starting!")
for i in range(10): print("Loop number", i)
print("Loop ended!")

Now go to the toolbar and click the save button. We’re going to call this “Indentation.py”. Once saved, click the green Run button, and you’ll see the results:

Ok, I think that’s enough for today. Try changing the range from 10 by adding a start and stop number like this:

for i in range(x, y):

With x and y being whatever numbers you choose.

For example, if you use range(3, 14), i will print as the numbers 3-13, since the last number is never included in the loop. If you want to print 1-10 instead of 0-9, you should use range(1, 11) and so on.

Thanks for Reading!

Next time, we will try a different kind of loop and explore what are known as “conditionals” that perform actions based on whether certain criteria are met. Until then, happy coding!

Posted on Leave a comment

How to Filter Data from an Excel File in Python with Pandas

5/5 – (1 vote)

Problem Formulation and Solution Overview

This article will show different ways to read and filter an Excel file in Python.

To make it more interesting, we have the following scenario:

Sven is a Senior Coder at K-Paddles. K-Paddles manufactures Kayak Paddles made of Kevlar for the White Water Rafting Community. Sven has been asked to read an Excel file and run reports. This Excel file contains two (2) worksheets, Employees and Sales.

To follow along, download the kp_data.xlsx file and place it into the current working directory.


💬 Question: How would we write code to filter an Excel file in Python?

We can accomplish this task by one of the following options:


Method 1: Use read_excel() and the & operator

This method uses the read_excel() function to read an XLSX file into a DataFrame and an expression to filter the results.

This example imports the above-noted Excel file into a DataFrame. The Employees worksheet is accessed, and the following filter is applied:

👀 Give me the DataFrame rows for all employees who work in the Sales Department, and earn more than $55,000/annum.

Let’s convert this to Python code.

import pandas as pd cols = ['First', 'Last', 'Dept', 'Salary']
df_emps = pd.read_excel('kp_data.xlsx', sheet_name='Employees', usecols=cols)
df_salary = df_emps[(df_emps['Dept'] == 'Sales') & (df_emps['Salary'] > 55000)] df_salary.to_excel('sales_55.xlsx', sheet_name='Sales Salaries Greater Than 55K') 

The first line in the above code snippet imports the Pandas library. This allows access to and manipulation of the XLSX file. Just so you know, the openpyxl library must be installed before continuing.

The following line defines the four (4) columns to retrieve from the XLSX file and saves them to the variable cols as a List.

💡Note: Open the Excel file and review the data to follow along.

Import the Excel File to Python

On the next line in the code snippet, read_excel() is called and passed three (3) arguments:

  • The name of the Excel file to import (kp_data.xlsx).
  • The worksheet name. The first worksheet in the Excel file is always read unless stated otherwise. For this example, our Excel file contains two (2) worksheets: Employees and Sales. The Employees worksheet can be referenced using sheet_name=0 or sheet_name='Employees'. Both produce the same result.
  • The columns to retrieve from the Excel workheet (usecols=cols).

The results save to df_emps.

Filter the DataFrame

The highlighted line applies a filter that references the DataFrame columns to base the filter on and the & operator to allow for more than one (1) filter criteria.

In Python, this filter:

df_salary = df_emps[(df_emps['Dept'] == 'Sales') & (df_emps['Salary'] > 55000)]

Equates to this:

👀 Give me the DataFrame rows for all employees who work in the Sales Department, and earn more than $55,000/annum.

These results save to sales_55.xlsx with a worksheet ‘Sales Salaries Greater Than 55K‘ and placed into the current working directory.

Contents of Filtered Excel File

YouTube Video

Method 2: Use read_excel() and loc[]

This method uses the read_excel() function to read an XLSX file into a DataFrame and loc[] to filter the results. The loc[] function can access either a group of rows or columns based on their label names.

This example imports the above-noted Excel file into a DataFrame. The Employees worksheet is accessed, and the following filter is applied:

👀 Give me the DataFrame rows for all employees who work in the IT Department, and live in the United States.

Let’s convert this to Python code.

import pandas as pd
from openpyxl import load_workbook cols = ['First', 'Last', 'Dept', 'Country']
df_emps = pd.read_excel('kp_data.xlsx', sheet_name='Employees', usecols=cols)
df_it = df_emps.loc[(df_emps.Dept == 'IT') & (df_emps.Country == 'United States')] book = load_workbook('kp_data.xlsx')
writer = pd.ExcelWriter('kp_data.xlsx', engine='openpyxl')
writer.book = book
df_it.to_excel(writer, sheet_name = 'IT - US')
writer.save()
writer.close()

The first line in the above code snippet imports the Pandas library. This allows access to and manipulation of the XLSX file. Just so you know, the openpyxl library must be installed before continuing.

The following line imports openpyxl. This is required, in this case, to save the filtered results to a new worksheet in the same Excel file.

The following line defines the four (4) columns to retrieve from the XLSX file and saves them to the variable cols as a List.

💡Note: Open the Excel file and review the data to follow along.

Import the Excel File to Python

On the next line in the code snippet, read_excel() is called and passed three (3) arguments:

  • The name of the Excel file to import (kp_data.xlsx).
  • The worksheet name. The first worksheet in the Excel file is always read unless stated otherwise. For this example, our Excel file contains two (2) worksheets: Employees and Sales. The Employees worksheet can be referenced using sheet_name=0 or sheet_name='Employees'. Both produce the same result.
  • The columns to retrieve from the Excel worksheet (usecols=cols).

The results save to df_it.

Filter the DataFrame

The highlighted line applies a filter using loc[] and passes the filter to return specific rows from the DataFrame.

In Python, this filter:

df_it = df_emps.loc[(df_emps.Dept == 'IT') & (df_emps.Country == 'United States')]

Equates to this:

👀 Give me the DataFrame rows for all employees who work in the IT Department, and live in the United States.

Saves Results to Worksheet in Same Excel File

In the bottom highlighted section of the above code, the Excel file is re-opened using load_workbook(). Then, a writer object is declared, the results filtered, and written to a new worksheet, called IT - US and the file is saved and closed.

YouTube Video

Method 3: Use read_excel() and iloc[]

This method uses the read_excel() function to read an XLSX file into a DataFrame and iloc[] to filter the results. The iloc[] function accesses either a group of rows or columns based on their location (integer value).

This example imports required Pandas library and the above-noted Excel file into a DataFrame. The Sales worksheet is then accessed.

This worksheet contains the yearly sale totals for K-Paddles paddles. These results are filtered to the first six (6) rows in the DataFrame and columns shown below.

import pandas as pd cols = ['Month', 'Aspire', 'Adventurer', 'Maximizer']
df_sales = pd.read_excel('kp_data.xlsx', sheet_name='Sales', usecols=cols)
df_aspire = df_sales.iloc[0:6]
print(df_aspire)

The results are output to the terminal.

Month Aspire Adventurer Maximizer
0 1 2500 5200 21100
1 2 2630 5100 18330
2 3 2140 4550 22470
3 4 3400 5870 22270
4 5 3600 4560 20960
5 6 2760 4890 20140

Method 4: Use read_excel(), index[] and loc[]

This method uses the read_excel() function to read an XLSX file into a DataFrame in conjunction with index[] and loc[] to filter the results. The loc[] function can access either a group of rows or columns based on their label names.

This example imports the required Pandas library and the above-noted Excel file into a DataFrame. The Sales worksheet is then accessed. This worksheet contains the yearly sale totals for K-Paddles paddles.

These results are filtered to view the results for the Pinnacle paddle using index[] and passing it a start and stop position (stop-1).

import pandas as pd cols = ['Month', 'Pinnacle']
df_pinnacle = pd.read_excel('kp_data.xlsx', sheet_name='Sales', usecols=cols)
print(df_pinnacle.loc[df_pinnacle.index[0:5], ['Month', 'Pinnacle']])

The results are output to the terminal.

Month Pinnacle
0 1 1500
1 2 1200
2 3 1340
3 4 1130
4 5 1740
YouTube Video

Method 5: Use read_excel() and isin()

This method uses the read_excel() function to read an XLSX file into a DataFrame using isin() to filter the results. The isin() function filters the results down to the records that match the criteria passed as an argument.

This example imports required Pandas library and the above-noted Excel file into a DataFrame. The Employees worksheet is then accessed.

These results are filtered to view the results for all employees who reside in Chicago.

import pandas as pd cols = ['First', 'Last', 'City']
df_emps = pd.read_excel('kp_data.xlsx', sheet_name='Employees', usecols=cols)
print(df_emps[df_emps.City.isin(['Chicago'])])

The results are output to the terminal.

First Last City
2 Luna Sanders Chicago
3 Penelope Jordan Chicago
9 Madeline Walker Chicago
34 Caroline Jenkins Chicago

Summary

This article has provided five (5) ways to filter data from an Excel file using Python to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd
Posted on Leave a comment

Hex String to Hex Integer in Python

5/5 – (1 vote)

💬 Question: Given a hexadecimal string such as '0xf' in Python. How to convert it to a hexadecimal number in Python so that you can perform arithmetic operations such as addition and subtraction?

The hexadecimal string representation with the '0x' prefix indicates that the digits of the numbers do have a hexadecimal base 16.

In this article, I’ll show you how to do some basic conversion and arithmetic computations using the hexadecimal format. So, let’s get started! 👇

Convert Hex to Decimal using int()

You can convert any hexadecimal string to a decimal number using the int() function with the base=16 argument. For example, '0xf' can be converted to a decimal number using int('0xf', base=16) or simply int('0xf', 16).

>>> int('0xf', base=16)
15
>>> int('0xf', 16)
15

Hexadecimal Number to Integer Without Quotes

Note that you can also write the hexadecimal number without the string quotes like so:

>>> 0xf
15

The 0x prefix already indicates that it is a hexadecimal number.

Using the eval() Function

That’s why an alternative way to convert a hexadecimal string to a numerical value (integer, base 10) is to use the eval('0xf') function like so:

>>> eval('0xf')
15

However, I wouldn’t recommend it over the int() function as the eval() function is known to be a bit tricky and poses some security risks.

Hex Arithmetic Operators

You can simply add or subtract two hexadecimal numbers in Python by using the normal + and - operators:

>>> 0xf + 0x1
16
>>> 0xf - 0xa
5
>>> 0x1 + 0x1
2

The result is always shown in decimal values, i.e., with base=10.

You can display the result with base=16 by converting it back to a hexadecimal format using the hex() built-in function. For example, the expression hex(0x1 + 0x1) yields the hexadecimal string representation '0x2'.

YouTube Video

Here are a couple of examples:

>>> hex(0x1 + 0x1) '0x2'
>>> hex(0xf + 0xf) '0x1e'
>>> hex(0xf * 16) '0xf0'

In the last line, you multiply with the base 16 which essentially shifts the whole number one digit and inserts a 0 digit at the right—much like multiplying with base 10 in a decimal system.

Adding Two Hex Strings

In the following example, you add together two hex strings '0xf' and '0xf'—both representing the decimal 15 so the result is decimal 30:

>>> int('0xf', 16) + int('0xf', 16)
30

If you need the result as a hex string, you can pass the whole computation into the hex() built-in function to obtain a hexadecimal representation of the decimal 30:

>>> hex(int('0xf', 16) + int('0xf', 16)) '0x1e'

Subtracting and Multiplying Two Hex Strings

You can also subtract or multiply two hex strings by converting them to integers from their base 16 representations using int(hex_str, 16), doing the computation in the decimal system using the normal - and * operators, and converting back to hexadecimal strings using the hex() function on the result.

See here:

>>> h1 = '0xf'
>>> h2 = '0x1'
>>> h1_int = int(h1, 16)
>>> h2_int = int(h2, 16)
>>> hex(h1_int - h2_int) '0xe'
>>> hex(h1_int * h2_int) '0xf'

Printing Hex String without Prefix ‘0x’

To print the hexadecimal string such as '0xffffff' without the '0x' prefix, you can simply use slicing hex_string[2:] starting from the third character and slice all the way to the right.

A minimal example:

>>> hex_string = '0xfffffff'
>>> hex_string[2:] 'fffffff'

Where to Go From Here?

Thanks for reading through the whole article, I’d love to see you around more often in the Finxter community to learn and improve your coding skills. ❤

If you also want to learn, join our free email academy and download our cheat sheets here:

Posted on Leave a comment

Python | Split String at Position

Rate this post

Summary: You can split a given string at a specific position/index using Python’s stringslicing syntax.

Minimal Example:

# Method 1:
s = "split string at position"
print(s[:12])
print(s[13:]) # Method 2:
import re
s = "split string at position"
pos = re.search('at', s)
l = s[:pos.start()]
r = s[pos.start():]
print(l)
print(r) # OUTPUT:
split string
at position

Problem Formulation

💬Problem: Given a string, how will you split the given string at any given position?

Let’s have a look at a couple of examples that demonstrate what the problem asks you to do:

Example 1

The following problem requires us to split the string into two parts. You have to cut the given string into two halves based on a certain index/position. The given cut position/index is 12.

# Input
s = "split string at position"
# Output
split string
at position

Example 2

The following problem asks us to split the string based on the position of a certain character (“,”) and a word (“or”) present in the string. Thus, in this case, you have not been given the exact position or index to split the string. Instead, you have to find the index/position of certain characters and then split the string accordingly based on the positions of the given characters and words and store the required sub-strings in different variables.

# Input
text = "Bob is the Relationship Manager, contact him at bob@xyz.abc or call him at 6546 "
# Output:
Personnel: Bob is the Relationship Manager
Email: contact him at bob@xyz.abc
Contact Info: call him at 6546

Now, let’s dive into the different ways of solving this problem.

Method 1: Using String Slicing

String slicing is the concept of carving a substring from a given string. Use slicing notation s[start :stop: step] to access every step-th element starting from index start (included) and ending in index stop (excluded). All three arguments are optional, so you can skip them to use the default values (start = 0, stop = len(string), step = 1.)

🌎 Related Tutorial: String Slicing in Python.

Example 1 Solution

Approach: Use string slicing to cut the given string at the required position. To do this, you have to use the square-bracket syntax within which you can specify the starting and ending indices to carve out the required sub-strings as shown in the solution below.

Code:

s = "split string at position"
print(s[:12])
print(s[13:])

Output:

split string
at position

Example 2 Solution

Approach: Use the index() method of the given character, i.e., “,” and the substring “or” within the given string. Then use this index to extract the required chunks of substrings by splitting the given string with the help of string slicing.

Code:

text = "Bob is the Relationship Manager, contact him at bob@xyz.abc or call him at 6546 "
# get the position of characters where you want to split the string
pos_comma = text.index(',')
pos_or = text.index('or')
# Slice the string based on the position of comma
personnel, email, phone = text[:pos_comma], text[pos_comma+1:pos_or], text[pos_or+2:]
print(f'Personnel: {personnel}\nEmail: {email}\nContact Info: {phone}')

Output:

Personnel: Bob is the Relationship Manager
Email: contact him at bob@xyz.abc Contact Info: call him at 6546 

Note: The index() method allows you to find the index of the first occurrence of a substring within a given string. You can learn more about Python’s index() method here: Python String index().

Method 2: Using regex

If a regular expression matches a part of your string, a lot of helpful information comes with it, for example, you can find out what’s the exact position of the match. The re.search(pattern, string) method is used to match the first occurrence of a specified pattern in the string and returns a match object. Thus, you can use it to solve the given problem.

🌎 Related read: Python Regex Search

Pre-requisite: match_object.start() is a method used to get the position of the first character of the match object and match_object.end() is the method to get the last character of the match object.

A Quick Look at The Official Documentation:

source: https://docs.python.org/3/library/re.html#re.Match.start

Example 1 Solution

Approach:

  • Import the regex module and then create a match object by using the re.search() method. You can do this by passing the substring/character that lies at the given split index/position. In this case, the substring that lies at the split index is “at“.
  • We can then split the string by accessing the start position of the matched string object by calling the method pos.start() where pos denotes the matched object. 
  • Then to get the first half of the split string, you can use string slicing as s[:pos.start()]. Here, we sliced the original string from the start index of the given string until the index of the searched character (not included) that was extracted in the previous step.
  • Further, we need the second section of the split string. Thus, we will now slice the original string from the index of the searched character to the end of the string, like so: s[pos.start():]

Code:

import re s = "split string at position"
pos = re.search('at', s)
l = s[:pos.start()]
r = s[pos.start():]
print(l)
print(r)

Output:

split string
at position

Example 2 Solution

The idea is pretty similar to the solution of example 1. You just need to adjust the start and stop indices within the slice syntax with the help of the start() and end() methods to extract the required split sub-strings one by one.

Code:

import re
text = "Bob is the Relationship Manager, contact him at bob@xyz.abc or call him at 6546"
# Look for the match objects
_comma = re.search(',', text)
_or = re.search('or', text)
# slice to get first substring
personnel = text[:_comma.start()]
# slice to get second substring
email = text[_comma.end()+1:_or.start()]
# slice to get third substring
phone = text[_or.end():]
# Final Output
print(f'Personnel: {personnel}\nEmail: {email}\nContact Info: {phone}')

Output:

Personnel: Bob is the Relationship Manager
Email: contact him at bob@xyz.abc or
Contact Info: call him at 6546

Conclusion

Woohoo! We have successfully solved splitting a string at the position using two different ways. I hope you enjoyed this article and it helps you in your coding journey. Please subscribe and stay tuned for more such interesting articles!

Related Reads:
⦿ Python | Split String by Whitespace
⦿
 How To Cut A String In Python?
⦿ Python | Split String into Characters


Google, Facebook, and Amazon engineers are regular expression masters. If you want to become one as well, check out our new book: The Smartest Way to Learn Python Regex (Amazon Kindle/Print, opens in new tab).

Posted on Leave a comment

6 Ways to Remove Python List Elements

5/5 – (2 votes)

Problem Formulation and Solution Overview

This article will show you how 6 ways to remove List elements in Python.

To make it more interesting, we have the following running scenario:

Suppose you have a Christmas List containing everyone to buy a gift for. Once a gift is purchased, remove this person from the List. Once all gifts have been purchased, remove the entire List.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']

💬 Question: How would we write code to remove items from a Python List?

We can accomplish this task by one of the following options:


Method 1: Use the del Keyword

This method uses Python’s del Keyword and highlights its ability to remove one List element and all List elements.

Remove One List Element

In this scenario, Asa's gift has been purchased and will be removed from the List.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
del xmas_list[3]
print(xmas_list)

As shown on the highlighted line, Asa is removed from the List by using del, referencing xmas_list and specifying Asa’s location ([3]).

When xmas_list is output to the terminal, the following displays.

['Anna', 'Elin', 'Inger', 'Sofie', 'Gunnel', 'Linn']

Remove All List Elements

In this scenario, all gifts have been purchased, and all List elements will be removed.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
del xmas_list
print(xmas_list)

As shown on the highlighted line, all elements of xmas_list are removed by using del and referencing xmas_list.

When xmas_list is output to the terminal, the following error is generated.

NameError: name 'xmas_list' is not defined

💡Note: This error is generated because the variable xmas_list no longer exists in memory.

YouTube Video

Method 2: Use remove() and a For Loop

This example uses the remove() function in conjunction with a for loop to remove one List element and all List elements.

Remove One List Element

In this scenario, Elin's gift has been purchased and will be removed from the List.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
xmas_list.remove('Elin')
print(xmas_list)

As shown on the highlighted line, Elin is removed from the List using the remove() function and passing Elin’s name as an argument.

When xmas_list is output to the terminal, the following displays.

['Anna', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']

Remove All List Elements

In this scenario, all gifts have been purchased, and all List elements will be removed.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
for item in xmas_list.copy(): xmas_list.remove(item)
print(xmas_list)

As shown on the first highlighted line, a for loop is instantiated. This loop declares a shallow copy of the List to iterate.

On each iteration, the remove() function is called and passed the current name in xmas_list as an argument (see below) and removed.

For example:

Anna
Elin
Inger
Asa
Sofie
Gunnel
Linn

When xmas_list is output to the terminal, an empty List displays.

[]

💡Note: A shallow copy creates a reference to the original List. For further details, view the video below.

YouTube Video

Method 3: Use slicing

This method uses slicing to remove one List element and all List elements.

Remove One List Element

In this scenario, Anna's gift has been purchased and will be removed from the List.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
xmas_list = xmas_list[1:]
print(xmas_list)

As shown on the highlighted line, Anna is removed from the List using slicing.

When xmas_list is output to the terminal, the following displays.

['Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']

Remove All List Elements

In this scenario, all gifts have been purchased, and all List elements will be removed.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
xmas_list = []
print(xmas_list)

As shown on the highlighted line, all List elements are removed by declaring an empty List.

When xmas_list is output to the terminal, an empty List displays.

[]
YouTube Video

Method 4: Use pop()

This method uses the pop() function to remove one List element and all List elements.

Remove One List Element

In this scenario, Linn's gift has been purchased and will be removed from the List.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
xmas_list.pop()
xmas_list.pop(2)
print(xmas_list)

As shown on the first highlighted line, the pop() method is appended to the xmas_list. This lets Python know to remove a List element from said List. Since no element is specified, the last element is removed (Linn).

On the second highlighted line, the pop() method is appended to the xmas_list and passed one (1) argument: the element to remove (2). This action removes Inger.

When xmas_list is output to the terminal, the following displays.

['Anna', 'Elin', 'Asa', 'Sofie', 'Gunnel']

💡Note: Both Linn and Inger are no longer in xmas_list.

Remove All List Elements

In this scenario, all gifts have been purchased, and all List elements will be removed.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn'] for i in xmas_list.copy(): xmas_list.pop()
print(xmas_list)

As shown on the first highlighted line, a for loop is instantiated. This loop declares a shallow copy of the List to iterate.

On each iteration, the pop() method is called. Since no argument is passed, the last element is removed.

When xmas_list is output to the terminal, an empty List displays.

[]
YouTube Video

Method 5: Use List Comprehension

This method uses List Comprehension to remove all List elements that do not meet the specified criteria.

Remove One List Element

In this scenario, Gunnel's gift has been purchased and will be removed from the List.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
xmas_list = [value for value in xmas_list if value != 'Gunnel']
print(xmas_list)

When xmas_list is output to the terminal, the following displays.

['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Linn']

💡Note: To remove all List elements, pass it empty brackets as shown follows: (xmas_list = []).

YouTube Video

Method 6: Use clear()

This method uses clear() to remove all List elements.

In this scenario, all gifts have been purchased, and all List elements will be removed.

xmas_list = ['Anna', 'Elin', 'Inger', 'Asa', 'Sofie', 'Gunnel', 'Linn']
xmas_list.clear()
print(xmas_list)

As shown on the highlighted line, all List elements are removed by appending the clear() function to xmas_list.

When xmas_list is output to the terminal, an empty List displays.

[]
YouTube Video

Summary

This article has provided six (6) ways to remove List elements to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programming Humor

💡 Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.

~~~

  • Question: Why do Java programmers wear glasses?
  • Answer: Because they cannot C# …!

Feel free to check out our blog article with more coding jokes. 😉

Posted on Leave a comment

Python | Split String by Whitespace

Rate this post

Summary: Use "given string".split() to split the given string by whitespace and store each word as an individual item in a list.
Minimal Example:
print("Welcome Finxter".split())
# OUTPUT: [‘Welcome’, ‘Finxter’]

Problem Formulation

Problem: Given a string, How will you split the string into a list of words using whitespace as a separator/delimiter?

Let’s understand the problem with the help of a few examples:

Example 1:
Input: text = “Welcome to the world of Python”
Explanation: Split the string into a list of words using a space ” ” as the delimiter to separate the words from the given string.
Output:
[‘Welcome’, ‘to’, ‘the’, ‘world’, ‘of’, ‘Python’]

Example 2:
Input:
text = “””Item_1
Item_2
Item_3″””
print(text.split(‘\n’))
Explanation: Split the string into a list of words using a newline “\n” as the delimiter to separate the words from the given string.
Output: [‘Item_1’, ‘Item_2’, ‘Item_3’]

Example 3:
text = “This is just a random text:\n New Line”
Explanation: The given string contains a combination of whitespaces between the words, such as space, multiple-spaces, a tab and a new line character. All of these whitespace characters have to be considered as delimiters while separating the words from the given string and storing them as items in a list. Here’s how the output looks:
Output:
[‘This’, ‘is’, ‘just’, ‘a’, ‘random’, ‘text:’, ‘New’, ‘Line’]

So, we have two situations at hand. One, that has a single whitespace used as a delimiter and another that has multiple whitespace characters as delimiters in the same string. Let’s dive into the numerous ways of solving this problem.

Method 1: Using split()

split() is a built-in method in Python which splits the string at a given separator and returns a split list of substrings. Here’s a minimal example that demonstrates how the split function works – finxterx42'.split('x') will split the string with the character ‘x’ as the delimiter and return the following list as an output: ['fin', 'ter', '42']. The default separator, i.e., when no value is passed to the split function is considered as any whitespace character, i.e., it will take into account any whitespace such as ‘\n’, ” “, ‘\t’, etc.

Read more about the split() method in this blog tutorial: Python String split().

Approach: Thus to split a string based on a given whitespace delimiter, you can simply pass the specific whitespace character as a separator/delimiter to the split('whitespace_character') function.

Code:

# Example 1:
text = "Welcome to the world of Python"
print(text.split(' '))
# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:
text = """Item 1
Item 2
Item 3"""
print(text.split('\n'))
# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3: text = "This is just a\trandom text:\nNew Line"
print(text.split()) # OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']

Note that to separate the words in the third example we did specify any separator within the split() function. This is because when you don’t specify the separator, then Python will automatically consider that any whitespace character that occurs within the given string is a separator.

Method 2: Using regex

Another extremely handy way of separating a string with whitespace characters as separators is to use the regex library.

Approach 1: Import the regex library and use its split method as re.split('\s+', text) where ‘\s+’ returns a match whenever the string contains one or more whitespace characters. Therefore, whenever any whitespace character is encountered, the string will be separated at that point.

Code:

import re
# Example 1:
text = "Welcome to the world of Python"
print(re.split('\s+', text))
# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:
text = """Item_1
Item_2
Item_3"""
print(re.split('\s+', text))
# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3:
text = "This is just a\trandom text:\nNew Line"
print(re.split('\s+', text))
# OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']

Related Tutorial: Python Regex Split

Approach 2: Another way of using the regex library to solve this question is to use the findall() method of the regex library. Import the regex library and use re.findall(r'\S+', text) where the expression returns all the characters/words in a list that do not contain any whitespace character. This essentially means that whenever Python finds and segregates a string that has no whitespace in it. As soon as a whitespace character is found it considers that as a breakpoint, therefore the next word that has a continuous sequence of characters without the presence of any whitespace character is taken into account.

Here’s a graphical representation of the above explanaton:

Code:

import re
# Example 1:
text = "Welcome to the world of Python"
print(re.findall(r'\S+', text))
# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:
text = """Item_1
Item_2
Item_3"""
print(re.findall(r'\S+', text))
# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3:
text = "This is just a random text:\n New Line"
print(re.findall(r'\S+', text))
# OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']

Related Tutorial: Python re.findall() – Everything You Need to Know

Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

Conclusion

We have successfully solved the given problem using different approaches. I hope you enjoyed this article and it helps you in your Python coding journey. Please subscribe and stay tuned for more interesting articles!

Related Reads:
⦿ How To Split A String And Keep The Separators?
⦿
 How To Cut A String In Python?
⦿ Python | Split String into Characters


Python Regex Course

Google engineers are regular expression masters. The Google search engine is a massive text-processing engine that extracts value from trillions of webpages.  

Facebook engineers are regular expression masters. Social networks like Facebook, WhatsApp, and Instagram connect humans via text messages

Amazon engineers are regular expression masters. Ecommerce giants ship products based on textual product descriptions.  Regular expressions ​rule the game ​when text processing ​meets computer science. 

If you want to become a regular expression master too, check out the most comprehensive Python regex course on the planet: