Python Strings | tutorial 4

How to add single quotes, double quotes, or both quotes in the python strings?

Example:

course = "Python's for everyone"
print(course)
new_course = 'Python for "EveryOne"'
print(new_course)
email = '''
Hi John!,

Welcome to helperscript to learn Python's for "Everyone"

Thank you,
Support Team
'''
print(email)
The output of String declaration – python 3

Triple quotes (”’Python for “Everyone””’) – Three single quotes from the start and three single quotes from the end. This type of string escapes all the symbols in the string.

Split string into an array (or) Split the string in python

Python string starts index with zero(0).

Example: course variable has string “Python for Everyone”

Course = ‘Python for Everyone’

Get the first character of a string in python

course[0]   

Get the second character of a string in python

course[1]  

Get the last character of a string in python

course[-1]

Get the last second character of a string in python

course[-2]

Get the first three character of a string in python

course[0:3]

Remove the first character and remove the last 3 characters of a string in python

course[1:-3]

Remove the character after 6 index

course[:6]

Remove the first 6 characters in the string

course[6:]

Clone or copy the string

course[:]

Code: 

# strings
course = 'Python for Everyone'
print(course);
print('course[0] = ' + course[0])
print('course[1] = ' + course[1])
print('course[-1] = ' + course[-1])
print('course[-2] = ' + course[-2])
print('course[0:3] = ' + course[0:3])
print('course[1:-3] = ' + course[1:-3])
print('course[:5] = ' + course[:6])
print('course[6:] = ' + course[6:])
print('course[:] = ' + course[:])

OUTPUT:

String Concatenation

Two ways to concat the string dynamically.

Normal way – firstname +’ ’+ lastname +’ is a coder’
Format way – f‘{firstname} {lastname} is a code’

f – prefix with f define a formatted string

Code:

string concatenation in python

Python strings method

Let,
course = ‘Python for Beginners’

# find the length of string
len(course)

# convert uppercase
course.upper()

# convert lowercase
course.lower()

# convert first character uppercase in each word
course.title()

# find an index of character or sequence of character.

 Python find() method is case sensitive.

print(course.find(‘P’))  # gives index of capital P
print(course.find(‘p’))  # return -1 if not present. 
print(course.find(‘Beginners’))

# Replace a character
course.replace(‘P’, ‘J’)

# Replace a sequence of character
course.replace(‘Python’, ‘Angular’)

# find a string contains in the existing string(case sensitive)
‘Python’ in course

App.py

course = 'Python for Beginners'
# find the length of string
print(len(course))
# convert uppercase
print(course.upper())
# convert lowercase
print(course.lower())
# convert first character uppercase in each word
print(course.title())
# find index of character or sequence of character
print(course.find('P'))  # capital
print(course.find('p'))  # small letter
print(course.find('Beginners'))
# Replace a character
print(course.replace('P', 'J'))
# Replace a sequence of character
print(course.replace('Python', 'Angular'))
# find a string contains in existing string
print('Python' in course) # gives boolean output either True or False
String Methods in python 3

In Next article, we see about Operators in Python.

PYTHON variables | tutorial 3

Python is a case sensitive language. So when you define a variable you should consider the uppercase and lowercase.

eg: price = 10 is different to PRICE = 10

Important Variable Types and Declaration

price = 10
# price variable type is INTEGER
# price is an identifier for variable and initialised with the value 10

update_price = 20.5
# update_price variable type is FLOAT

is_published = True
# is_published variable type is BOOLEAN
# either True or False (case sensitive first letter should be capital)

name = 'Jasim'
# name variable type is STRING

# – is a comment line. Python interpreted not read this line.

Let’s do one small task.
Variable Declaration Task: We check in a patient named John Toe. He’s 20 years old and is a new patient.

name = 'John Toe'
Age = 20
is_new_patient = True

As of now we successfully learn how to declare the variable in python. Next, we learn about how to get input from users.

Instead of print() method use input() method to get the input from the user.

Filename: app.py

name = input('What is your name? ')
print('Hey! ' + name)
In your terminal, interpreted python will wait for your input. In my case, I type John Carter and then hit enter.

Task 2: Ask two questions – Person’s name and his favorite color. Print the output like “John Toe like violet”.

name = input('What is your name? ')
Color = input('what is your favourite color? ')
print(name + ' like ' + color);
The output of program – python input/print

Type conversion

Type conversion is used to define a variable for calculation. If the number is in string format we need to convert the number string into the integer type.

Example:

birth_year = input('Your birth year? ')
print(type(birth_year))
age = 2020 - birth_year
print('Your age is ' + age)
You will get an error – TypeError: Unsupported operand type(S) for int and str

You get input from the terminal 1994 and the type of 1994 is string identified with the use of type() method.

You get an error in line 20 in the app.py file. It will be shown in the terminal due to the type differentiation. So how to solve this problem. We need to convert the type from string to integer.

How to convert the string to integer

int() – method is used to convert the typed string to an integer.
str() – method is used to convert the integer type to string type.

Solution:

birth_year = input('Your birth year? ')
print(type(birth_year))
age = 2020 - int(birth_year)
print('Your age is ' + str(age))
output: Type conversion example

In the next article let see the strings in python. Go the next continuation on the menu.

Basics of python tutorial 2

Open your PyCharm or your favorite IDE. Click to create a new project and name your project.

Give your project name and check the base interpreter has the current version. If you need another version, you can select the other version from the list.

Create a first python program

Name your file. In my case app.py

Now let’s start to learn the code first.

How to console or print the value in the python

file name: app.py

print('Hi! welcome to helperscript');

print(data) => print function helps to print or console in terminal output. It is used to identify whether the data passed are correct or incorrect.

data => you can pass data that you want to output. When your data is a string. String declaration with a single quote or either double quote.

Eg: print(“hello”) is equal to print(‘hello’)
Then Run the app.py file from the menu Run. It will show configuration settings. As of now we just run the file. So just click on the app.

After Run the app.py file. The below terminal will open and show the output like below.

output in console python

Python code gets executed line by line from the top.

Print the string with the multiplication

file name: app.py

print('Hi! welcome to helperscript')
print('*' * 5)
output of print(‘*’ * 5)

In python, the String data type can be generated and printed multiple times with an asterisk.

So the python is powerful for AI, Automation, desktop application, and web application. 

Let us see more new topics in python in the next article. Go to the menu of Python and find the next tutorial for continuation…

Python 3 tutorial step by step learning through free courses

INTRODUCTION TO PYTHON 3

Python is one of the most popular languages nowadays.

Python has the ability to do

  1. Automation
  2. AI (Artificial Intelligence)
  3. Applications
  4. Websites

We talk about all the core concepts in python and then we build three(3) python projects together.

BUILD WEB APPLICATION

Django administration

HOW TO USE 1000 OF SPREADSHEET IN MIN 100 SECONDS  WITH CHARTS

CHARTS IN SPREADSHEET USING PYTHON

Let’s start the course for the absolute beginners.

INSTALL PYTHON

HOW TO DOWNLOAD AND INSTALL PYTHON ON YOUR COMPUTER

  1. Go to python.org
  2. Click on downloads
  3. Click the Download button for the latest version

In windows simply click and open the downloaded file. Make sure you check Add path to the variable.

For Mac, Just continue and Agree with the license agreement and install it.

Install python in mac

Next, we are going to install a code editor. PyCharm (https://jetbrains.com/pycharm) is one of the best code editors for python. It fully depends on you. You can use another editor too.

Download and install pyCharm on your computer depends on your OS.

Windows => click next => next => and install

Mac => drag and drop the pyCharm to the application to install.

Choose your theme, Most of them use Dracula or blacky themes to protect their eyes. Now open your pyCharm application.

Congratulations, you are now successfully downloading and installing everything for python to learn.

Go to the python menu on top and see the continuation tutorial in the python.

Angular automated testing

In this article, we will learn more about automated testing in angular.

What is automated testing?
It is type of testing software without humans with lesser time. It helps you to catch the defects before releasing the software.

How to write a test coding in angular?
Before jumping into the test coding. Let see the different type of testing in angular.

Type of Testing in angular

  • Unit Testing (UT)
  • Integration Testing (IT)
  • End to End Testing (e2e)

Unit Testing
Test a component in Isolation, without external resources (e.g. file system, database, API endpoints).

  • Easiest to write
  • Superfast
  • Don’t give us much confidence.

Integration Tests
Test a component with external resources (e.g. file system, database, API endpoints)
Integration tests: component + template
Unit tests: component

End-to-end Tests

Test the entire application as a whole.

  • More confidence
  • Very slow
  • Very fragile

Let’s see the fundamental of Unit Testing
Tests are first-class citizens.

Clean Coding Practices

  • Small functions/ methods (10 lines of code or less)
  • Proper naming
  • Single responsibility

Example of Unit testing in angular
compute.ts

//function
compute(number){
if(number < 0){
return 0;
}else{
return number + 1;
}
}


Use jasime javascript library to write the test code.
Common function using in angular is
describe() // suite
it() // spec
expect() // ecpected value

compute.spec.ts // test file

import {compute} from '.compute'
describe('compute', () =>{
it('should return O if input is negative', () => {
const result = compute(-1);
expect(result).toBe(0);
})
})

Run the code with “ng test compute”

 As you can see in the above image "Executed 1 of 1 success".
Run the ng test command create a browser instantiated and show like below. Karma will connected.
angular karma listener

After click on debug and see it in the console will reply the same of the test result. You can save it in a file for your track.

debug angular

This is how Unit testing will write. In next article will see the integration testing and later end to end testing.

Top ten Javascript tricks part 5

“for in” vs “for of”

for(a in 'ab'){
console.log(a)
}
//0
//1

for(a of 'ab'){
console.log(a)
}
//a
//b

Record Timing

console.log('timer')
setTimeout(() => console.log, 1000)
console.timeEnd('timer')
// result: timer: 0.056884765625ms

Fibonacci sequence algorithm in Javascript

//while loop
function fibonacci(num){
let a = 1, b = 0 , temp;
while(num >= 0){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}

//Recursive solution
function fibonacci(num){
if(num <= 1) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}

//Memization
function fibonacci(num, memo){
memo = memo || {};
if(memo[num]) return memo[num];
if(num <= 1) return 1;
return memo[num] = fibonacci(num - 1, memo) + fibonacci(num - 2, memo)
}

One time event listeners in Javascript

const button = document.getElementById('button');

button.addEventListener("click", () => {
console.log('I will fire only once');
}, {once: true})

Private field declaration in es6 class

In Es6, private class fields are defined using a hash # prefix.
You can start using them today with babel7 and stage 3 preset

class Something{
#property;

constructor() {
this.#property = "Test property";
}
}

const instance =  new Something();
console.log(instance.property);
//Result: undefined

Code validator in new Es2020 features are now finalized

//old way
user && user.address && user.address.house &&
console.log(user.address.house.number)

// do this Es2020 beatury
console.log(user?.address?.house?.number)

Pipeline Operator

The experimental pipeline operator |> (current stage at 1) pipes the value of an expression into a function.
This allows the creation of chained function calls in a readable manner.
The result is syntactic sugar in which a function call with a single argument.
As of now, there is no Browser compatibility.

function doubleSay(str){
return str +", "+ str
}

function capitalize(str){
return str[0].toUpperCase() + str.substring(1)
}

function exclaim(str){
return str + '!'
}

let result = exclaim(capitalize(doubleSay("helperscript")))
console.log(result) // "Helperscript helperscript!"

result = "helperscript" |> doubleSay |> capitalize |> exclaim
console.log(result) // "Helperscript, helperscript!"

Static Vs Dynamic Import

import React from 'react';
// module exported with default keyword

import { FC } from 'react';
// module exported without default keyword

// Dynamic import
import('path/to/module.js').then((module) =>{
...
})

//or inside an async function
const module = await import('path/to/module.js');

Javascript padStart() and padEnd()

padStart() – The padding applied from start of string
padEnd() – Then padding applied from end of string

'helperscript'.padStart(14); // "  helperscript"
// if padString given
'helperscript'.padStart(14, '#') // "##helperscript"

//if padString not given
'helperscript'.padEnd(14) // "helperscript  "

// if padString given
'helperscript'.padEnd(14, '#') // "helperscript##"

String() Vs .toString() in javascript

The String () method converts anything into a string.
The toString() method converts numbers and booleans to a string.

String(68) // "68"
String(null) // "null"
String(undefined) //  "undefined"
String(true) // "true"


// toString()
(68).toString(); //"68"
(true).toString(); // "true"
(null).toString(); // TypeError
(undefined).toString(); // TypeError

But Unlike the String() method, the .toString() method will throw a TypeError, when used with null or undefined

Have a great day! Comment if any queries.

Top ten Javascript tricks part 4

Throw an error when parameters required for function

const requireParam = () => {
thorw new Error('This parameter is required')
}

const sumNumbers = (val1 = requiredParam(), val2 = requiredParam()) => {
return val1 + val2
}

sumNumbers(4, 5)
//Result: 9

sumNumbers(4, null)
//Result: 4

sumNumbers(4)
//Result: Uncaught Error: This  paramter is required

sumNumbers(4, undefined)
//Result: Uncaught Error: This  paramter is required

ES2018 new method “finally”

fetch(https://google.com).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
})  // es2018 finally
.finally(() => {
//your code here
})

ES5 getters and setters

const user = {
firstName: "John",
lastName: "Doe"
}

//fullname is a virtual field
get fullName(){
return this.firstName + '' + this.lastName
},

//validate age before saving
set age(value) {
if(isNaN(value)) throw Error('Age must be a number')
this._age = Number(value)
},

// get age(){
return this._age
}

console.log(user.fullName) // John Doe
user.firstName = "vignes"
console.log(user.fullName) // vignes Doe
user.age = '25'
console.log(user.age) // 25
user.age ="Invalid text" // Error: Age must be a number

Multiple conditions in an IF statement

const status = 'online';

// Classical approach
if(status === 'online' || status === 'away' || status === 'busy'){
console.log('Do Something');
}

// A better approach
if(['online', 'away', 'busy'].indexOf(status) ! === -1) {
console.log('Do Something')
}

// Check indexOf with ~ operator
if(~['online', 'away', 'busy'].indexOf(status)){
console.log('Do Something')
}

// Even Better, using includes method => Favourite
if(['online', 'away', 'busy'].includes(status)){
console.log('Do Something')
}

Type coercion in Js
Type Coercion is the conversion of one type of object to a new object of a different type with similar content. Tapestry frequently must coerce objects from one type to another

console.log(false === 0) // true
console.log(true + false) // 1
console.log('val' + 40 + 60) // val4060
console.log(40 + 6 + 'val') // 46val
console.log('8' + 1) // 81
console.log('10' - 2) // 8
console.log(6 * null) // 0

ES6 startsWith() and endsWith()

const image ='hill-mountain.png';
const validImage = image.endsWith('.png');
// result: true

const hillMountain = 'Hill Mountain';
const startsWith = hillMountain.startsWith('Hill');
// result: true

Array.from()

The Array.from() methods crates a new shallowed copied array instance from an array or iterable object.

// Array from a string
Array.from('foo') 
//Result: ['f', 'o', 'o']

//Array form a set
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// Result get unique value: ['foo', 'bar', 'baz'] 


//Array from a Map
const mapper = new Map([ ['1', 'a'], ['2', 'b'] ]);
Array.from(mapper.values())
// ['a', 'b']

Array.from(mapper.keys());
//['1' , '2']

Array form an Array-like object (arguments)
function f(){
return Array.from(arguments)
}

f(1,2,3) //result [1, 2, 3]

//Using an arrow function as the map function to manipulate the elements
Array.from([1,2,3], x => x + x) 
// result [2, 4 , 6]

entries() method

The entries() method returns a new Array Iterator object that contains the key/ value pairs for each index in the array

const arr = ['a', 'b', 'c']
const iterator = arr.entries()
console.log(iterator.next().value) 
// Result: Array [0, "a"]
console.log(iterator.next().value)
//Result: Array [1, 'b']

Array replacer by JSON.stringify()

const user = {
'username': 'helperscripter',
'email': 'help@helperscript.com',
'password': 'yourpassword'
}

const userString = JSON.stirngify(user, ['username', 'email']);
//result: 
{
'username': 'helperscripter',
'email': 'help@helperscript.com'
}

Javascript some() and Every() functions

const moneyHeist = [
{name : 'Denvar', age: '25'},
{name : 'Oslo', age: '40'},
{name : 'Tokyo', age: '17'}
]

moneyHeist.every(el => el.age > 18)
//return  false

moneyHiest.some(el => el.age < 18 )
//return true

I hope you all enjoy these methods and tricks. Thanks for reading. Please comment if it is useful.

Top ten Javascript tricks part 3

Different ways to pass parameters to a setTimeout

const addNum = (a, b) => console.log(a + b); setTimeout(addNum, 1000, 2, 3) //result: 5 setTimeout(() => { addNum(2,3); },1000) //result: 5 setTimeout(addNum.bind(null, 2, 3), 1000); //result: 5

3 ways to get the Date and Time in milliseconds

new Date().getTime(); // 1576509862158 Date.now(); // 1576509862158 +new Date(); // 1576509862158

function() declaration in ES5 and ES6

// old way ES5
function tomAndJerry(){
}

// Es6
tomAndJerry() => {
}

Caching the array.length in the loop

let array = new Array(le9);

for(let i = 0; i < array.length; i++){
// this loop will calculate array length in each iteration
}

for(let i = 0; length =  array.length; i < array.length; i++){
// this loop will calculate array length only once
}

Different approaches to creating an HTML link

let myText = 'Click me please'

// usual way
`<a href="#">${myText}</a>`
// <a href="#">Click me please</a>

// Using link method
myText.link(#);
// <a href="#">Click me please</a>

Easily check the visibility of div or page

window.addEventListener('visiblitychange', ()=> {
// document => define any html element div, a, span
if(document.hidden){ 
console.log('div is hidden')
}else{
console.log('div is visible')
}
})

Check the data array or not? using isArray()

let array = [1,2,3,4]
let numb = 3

Array.isArray(array) // return true

Array.isArray(numb) // return false

Array.reduce()
It applies a function to each element in an array and reduces the array into a single element.

const arr = [5, 10, 15, 20, 25];

const result  = arr.reduce((total, currentValue) => {
console.log(currentValue); // 5 10 15 20 25
return total+currentValue;
});

console.log(result)
//result 75

How to verify that a given argument is a number

isNumber = (n) => {
return !isNaN(parseFloat(n)) isFinite(n);
}

isNumber(4) // true

isNumber(4.4) // true

isNumber('4') // false

Generate a random set of alphanumeric characters

// genreate random aplhanumeric
generateRandomAlphaNum = len =>{
var rdmString='';
for(; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.Substr(0, len);
}


generateRandomAlphaNum(5) // result blphj
generateRandomAlphaNum(11) // result: uug4th6ie2h
generateRandomAlphaNum(8) // result: rimbe38x

I hope this will help your developing skills. If any queries feel free in below comment section. Have a great day!.

Javascript tirck part 4 >

Top Ten javascript tricks – part 2

Converting Object to Array – ES2017

// Converting Object => Array

const zoo = {
lion : 'animal',
peacock: 'bird'
}

//Keys
Object.keys(zoo)
// ['lion', 'parrot']

//values
Object.values(zoo)
// ['animal', 'bird']

//keys and values
Object.entries(zoo)
//[['lion','animal'], ['peacock','bird']]

Different ways to convert float to integer

Math.floor(5.95)
// 5

Math.ceil(5.15)
// 6

Math.round(5.4)
// 5

Math.round(5.5)
// 6

console.log(5.95 | 0); // quick way
//result: 5

Merging Object: Multiple objects into a single Object using the spread operator

const person= {name:'Jasim', gender:'Male'};
const tools ={computer:'Mac', editor:'VScode'};

const summary = {...person, ...tools};
*/
{
name: 'jasim',
gender:'Male',
computer:'Mac',
editor:'Vscode'
  }
/*

Make Console.log() output colorful and stylish in the browser console

console.log("%c I am red %c I am green", "color:red", "color:green" );
I am red I am green

Remove Character from String

let str ='Hello';

// remove first character
str.slice(1) // ello

// remove last character
string.substring(1,str.length -1)
// Hell

//remove substring from string
str.replace('ello', i)
// Hi

//remove character "LL" from "Hello" with split and join
str.split('l').join('')
// Heo

Add new element or push new element into an Array

let array = ['H', 'i'];

// add new element at last
array.push('!'); 
// ['H', 'i','!']

//add element at first
array.unShift('!')
// ['!','H', 'i']

3 ways to concat the multidimensional array

let nestedArray = [ [1, 2, 3], [4, 5], [6, 7,8]];

//using Array.flat() method
nestedArray.flat()
//result : [1, 2, 3, 4, 5, 6, 7, 8]

//usign concat and apply
[].concat.apply([], nestedArray)
//result : [1, 2, 3, 4, 5, 6, 7, 8]

//usign concat with ...spread operator
[].concat(...nestedArray);
//result : [1, 2, 3, 4, 5, 6, 7, 8]

Naming Conventional

//Camel case => mostly for variable declaration (camelCase)

<p id="camelCase>Hello!</p>
var camelCase;

//Pascal case (PascalCase)
class PascalCase{}

//hyphen html attribute declaration
<p class="main-paragraph">Hello1</p>

Array sort()

let array = [40, 2, 3, 45, 25, 100]

//Old way
array.sort(function(a, b){ return a-b});
// [2, 3, 25, 40, 45, 100]

//New Es6 way
array.sort((a,b) => a - b)
// [2, 3, 25, 40, 45, 100]

Change the color of cursor (caret) – CSS

input {
caret-color: auto
}

input{
caret-color: red
}
// text the color of below input caret cursor

I hope you enjoying this beautiful tricks in javascript. The third part of the javascript tricks in the next article.



Part 3 javascript trick >

How to read the excel file in angular with XSLX package

Here we add example code for fetching data from excel.

Add XLSX package to the angular project

npm install xlsx –save

read excel data in angular

Download demo Excel

app.component.ts

uploadExcel(e) {
  
  try{
  
  const fileName = e.target.files[0].name;
  
  import('xlsx').then(xlsx => {
    let workBook = null;
    let jsonData = null;
    const reader = new FileReader();
    // const file = ev.target.files[0];
    reader.onload = (event) => {
      const data = reader.result;
      workBook = xlsx.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = xlsx.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      this.products = jsonData[Object.keys(jsonData)[0]];
      console.log(this.products);

    };
    reader.readAsBinaryString(e.target.files[0]);
  });

}catch(e){
   console.log('error', e);
}

}

app.component.html

 <input type="file" (change)="uploadExcel($event)">

  <table >
    <thead>
      <tr>
        <th>#</th>
        <th>Product Identity</th>
        <th>Product Name</th>
        <th>Product Price</th>
        <th>Seller Name</th>
        <th>Total Count</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let product of products; let i = index">
      <td>{{i+1}}</td>
        <td>{{product.identity}}</td>
        <td>{{product.name}}</td>
        <td>{{product.price}}</td>
        <td>{{product.sellerName}}</td>
        <td>{{product.count}}</td>
        <td>{{product.status}}</td>
      </tr>
    </tbody>
  </table> 

app.component.css

table{
  width:75%;
  margin:20px auto;
}
table tr td, table tr{
  border-collapse: collapse;
  border:1px solid #ccc;
  font-size:14px;
}

I hope this will help. If any queries feel free to comment below.