Categories
Python Answers

How to use if/else in a list comprehension in Python?

Sometimes, we want to use if/else in a list comprehension in Python.

In this article, we’ll look at how to use if/else in a list comprehension in Python.

How to use if/else in a list comprehension in Python?

To use if/else in a list comprehension in Python, we can write it in the following format:

[f(x) if condition else g(x) for x in sequence]

For instance, we write:

x = [1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a']  
x_non_str = [el for el in x if not isinstance(el, str)] 
print(x_non_str)

to use list comprehension and if/else to return an array with non-string elements.

We return anything in x that has not isinstance(el, str) return True.

Therefore, x_non_str is [1.5, 2.3, 4.4, 5.4, 1.5, 5.1].

Conclusion

To use if/else in a list comprehension in Python, we can write it in the following format:

[f(x) if condition else g(x) for x in sequence]
Categories
Python Answers

How to use a regular expression match a whole word with Python?

Sometimes, we want to use a regular expression match a whole word with Python.

In this article, we’ll look at how to use a regular expression match a whole word with Python.

How to use a regular expression match a whole word with Python?

To use a regular expression match a whole word with Python, we can use the re.search method with a regex to match a whole word.

For instance, we write:

import re

x = "this is a sample"
res = re.search(r'\bis\b', x)
print(res)

We call re.search with a regex that matches the word ‘is’.

\b indicates the word boundary.

The 2nd argument is the string that we’re searching for the matches for.

Therefore, res is <re.Match object; span=(5, 7), match='is'>.

Conclusion

To use a regular expression match a whole word with Python, we can use the re.search method with a regex to match a whole word.

Categories
Python Answers

How to parse data in JSON format with Python?

Sometimes, we want to parse data in JSON format with Python.

In this article, we’ll look at how to parse data in JSON format with Python.

How to parse data in JSON format with Python?

To parse data in JSON format with Python, we can use the json.loads method.

For instance, we write:

import json

data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print(data['two'])

We import the json module and call the json.loads method with a JSON string.

It returns a dictionary with the keys being the JSON object’s keys and the values being the JSON object’s values and we assign that to data.

Therefore, we see 2 printed.

Conclusion

To parse data in JSON format with Python, we can use the json.loads method.

Categories
Python Answers

How to select items randomly but weighted by probability with Python?

Sometimes, we want to select items randomly but weighted by probability with Python.

In this article, we’ll look at how to select items randomly but weighted by probability with Python.

How to select items randomly but weighted by probability with Python?

To select items randomly but weighted by probability with Python, we can call random.choice with the weights parameter set to the probability of each item being chosen.

For instance, we write:

import random

choices = random.choices(
  population=[['a','b'], ['b','a'], ['c','b']],
  weights=[0.2, 0.2, 0.6],
  k=10
)

print(choices)

We call random.choices with population set to the items that can be chosen.

weights has the probability of each item in population being chosen.

k is the number items to choose.

The items chosen are returned in a list and assigned to choices.

Therefore, choices is:

[['a', 'b'], ['c', 'b'], ['a', 'b'], ['c', 'b'], ['c', 'b'], ['c', 'b'], ['b', 'a'], ['a', 'b'], ['c', 'b'], ['a', 'b']]

Conclusion

To select items randomly but weighted by probably with Python, we can call random.choice with the weights parameter set to the probability of each item being chosen.

Categories
Python Answers

How to replace multiple substrings of a string in Python?

Sometimes, we want to replace multiple substrings of a string in Python.

In this article, we’ll look at how to replace multiple substrings of a string in Python.

How to replace multiple substrings of a string in Python?

To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.

For instance, we write:

def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text

d = { "cat": "dog", "dog": "pig"}
my_sentence = "This is my cat and this is my dog."
new_sentence = replace_all(my_sentence, d)
print(new_sentence)    

to create the replace_all function.

We loop through the dic dictionary’s key-value pairs which are returned by dic.items.

Then we call text.replace with i and j, which is the original substring and the replacement substring respectively.

And we assign the new returned string to text.

Finally, we return text which has all the replacements done.

Next, we call replace_all with my_sentence and d.

And new_sentence is 'This is my pig and this is my pig.'.

Conclusion

To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.