After JavaScript (EcmaScript), Python is my second favorite programming language. It has a very low learning curve, making it quite intuitive compared to other languages and its list of basic keywords is short. Any individual can quickly adapt, even those who have never written a line of code (but who understand English).
One of the basic Python keywords is in
, used to search for portions of text within a text string, list, dictionary or tuple.
if 'banana' in ('apple','pineapple','banana','pear'):
print 'Banana is a fruit'
else:
print 'Nop, is an animal'
if 'banana' in 'Tonight we will eat banana dessert':
print 'Cool, is banana tonight!'
else:
print "I'm not hungry"
JavaScript also has its in
but it is contingent on being an operator , usually tied to the loop for
by its limited way of reacting.
var fruits = ['apple','pineapple','banana','pear'];
for (var f in fruits)
{
var fruit = fruits[f];
console.log(fruit);
};
How about we emulate in
in JavaScript to evaluate a portion of text? Many times I have had to look for portions of text in a large string, so going over the matter here I show you a function that I prepared to which we can pass an array, a text string or a JavaScript object.
String.prototype.in = function(arr)
{
var str = String(this);
var arr = arr || [];
function accents (s)
{
s = String(s).toLowerCase().trim();
s = s.replace(/á|à|â|ã|ä|å|ā|æ/gi,'a');
s = s.replace(/é|è|ê|ë|ē|ę/gi,'e');
s = s.replace(/í|î|ï|ī/gi,'i');
s = s.replace(/õ|ó|ô|ö|ő|ō|ø|œ/gi,'o');
s = s.replace(/ú|ü|û|ů|ű|ŭ|ū/gi,'u');
s = s.replace(/ç|č|ĉ|ć/gi,'c');
s = s.replace(/š|ŝ|ś|ş/gi,'s');
s = s.replace(/ÿ|ý|ŷ/gi,'y');
s = s.replace(/ž|ź|ż/gi,'z');
s = s.replace(/ţ|ț/gi,'t');
s = s.replace(/ñ|ň/gi,'n');
s = s.replace(/ř/gi,'r');
s = s.replace(/ĵ/gi,'j');
s = s.replace(/ğ/gi,'g');
s = s.replace(/ŵ/gi,'w');
s = s.replace(/[^0-9a-z]/gi,'');
return s;
};
str = accents(str);
if ( typeof arr === 'object' )
{
arr = accents(JSON.stringify(arr));
};
if ( typeof arr === 'string' )
{
arr = accents(arr);
};
return arr.indexOf(str) > -1;
};
We apply it like this:
var fruits = ['apple','pineapple','banana','pear'];
// var fruits = [{ fruit: 'apple' }, { fruit: 'pineapple' }, { fruit: 'banana' }, { fruit: 'pear' }];
// var fruits = 'apple, pineapple, banana, pear';
var banana = 'banana';
if ( banana.in(fruits) )
{
console.log('Banana is a fruit');
} else {
console.log('Nop, is an animal');
};
If the word ‘banana’ is inside an array, a text string, or a JavaScript object, it will return true
, otherwise false
.
This will simplify our work a bit, don’t you think?