Entrepreneur – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Sun, 02 Mar 2025 08:21:04 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Entrepreneur – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Pandas – Drop Columns by Label | Index https://shishirkant.com/pandas-drop-columns-by-label-index/?utm_source=rss&utm_medium=rss&utm_campaign=pandas-drop-columns-by-label-index Sun, 02 Mar 2025 08:20:59 +0000 https://shishirkant.com/?p=4377 How to drop column(s) by index in Pandas? You can use the drop() function in Pandas to remove columns by index. Set the axis parameter to 1 (indicating columns) and specify either the single-column index or a list of column indices you want to eliminate.

In this article, I will explain how to drop column(s) by index using multiple ways of pandas such as the DataFrame.drop() function, DataFrame.loc[] function and DataFrame.iloc[].columns property.

Key Points –

  • Use the DataFrame.drop() method with the axis parameter set to 1 to drop columns by index.
  • Specify the column index or a list of column indices to drop multiple columns at once.
  • Dropping columns by index modifies the DataFrame in place unless the inplace parameter is set to False.
  • Provide either a single-column index or a list of column indices to be dropped.
  • To drop multiple columns, pass a list containing the indices of the columns you want to drop.

Quick Examples of Dropping Columns by Index

Below are some quick examples of dropping column(s) by an index in pandas.


# Quick examples of dropping columns by index

# Example 1: Using DataFrame.drop() method
df2=df.drop(df.columns[1], axis=1)

# Example 2: Drop first column with param inplace = True
df.drop(df.columns[1], axis=1, inplace = True)
                    
# Example 3: Drop columns based on column index
df2 = df.drop(df.columns[[0, 1, 2]],axis = 1)

# Example 4: Drop column of index 
# Using DataFrame.iloc[] and drop() methods
df2 = df.drop(df.iloc[:, 1:3],axis = 1)

# Example 5: Drop columns by labels 
# Using DataFrame.loc[] and drop() methods
df2 = df.drop(df.loc[:, 'Courses':'Fee'].columns,axis = 1)

To run some examples of drop column(s) by index. let’s create DataFrame using data from a dictionary.


# Create a Pandas DataFrame.
import pandas as pd
import numpy as np
technologies= {
    'Courses':["Spark","Spark","PySpark","JAVA","Hadoop",".Net","Python","AEM","Oracle","SQL DBA","C","WebTechnologies"],
    'Fee' :[22000,25000,23000,24000,26000,30000,27000,28000,35000,32000,20000,15000],
    'Duration':['30days','35days','40days','45days','50days','55days','60days','35days','30days','40days','50days','55days']
          }
df = pd.DataFrame(technologies)
print("Create DataFrame:\n", df)

Yields below output.

pandas drop columns index

Using DataFrame.drop() Column by Index

You can use DataFrame.drop() function to remove the column by index. The drop()function is used to drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axes, or by specifying the direct index of columns. When using a multi-index, labels on different levels can be removed by specifying the level.


# Using DataFrame.drop() method.
df2=df.drop(df.columns[1], axis=1)
print("After dropping the first column:\n", df2)

Yields below output. This deletes the second column as the index starts from 0.

pandas drop columns index

If you want to update the existing DataFrame instead of creating a new DataFrame after dropping it’s column you can use the inplace=True parameter of the drop() function. This function will return the original DataFrame with the remaining columns.


# Drop first column with param inplace = True
df.drop(df.columns[1], axis=1, inplace = True)
print("After dropping the first column:\n", df)

Yields below output.


# Output:
After dropping the first column:
             Courses Duration
0             Spark   30days
1             Spark   35days
2           PySpark   40days
3              JAVA   45days
4            Hadoop   50days
5              .Net   55days
6            Python   60days
7               AEM   35days
8            Oracle   30days
9           SQL DBA   40days
10                C   50days
11  WebTechnologies   55days

Drop Multiple Columns By Index

In this section, you’ll learn how to drop multiple columns by index. You can use df.columns[[index1, index2, indexn]] to identify the list of column names in that index position and pass that list to the drop method.


# Drop multiple columns based on column index
df2 = df.drop(df.columns[[1, 2]],axis = 1)
print("After dropping multiple columns:\n", df2)

Yields below output.


# Output:
After dropping multiple columns:
            Courses
0             Spark
1             Spark
2           PySpark
3              JAVA
4            Hadoop
5              .Net
6            Python
7               AEM
8            Oracle
9           SQL DBA
10                C
11  WebTechnologies

Drop Columns Using DataFrame.iloc[] and drop() Methods

To drop columns using DataFrame.iloc[] and drop() methods, you specify the index positions of the columns you want to drop using iloc[]. For instance, df.iloc[:, 1:3] selects all rows (:) and columns from index position 1 up to, but not including, index position 3. This selects columns at index positions 1 and 2, which are Fee and Duration. Then you can use df.drop() to drop these selected columns along the specified axis (axis=1 for columns).


# Drop column of index 
# Using DataFrame.iloc[] and drop() methods
df2 = df.drop(df.iloc[:, 1:3],axis = 1)
print("After dropping multiple columns:\n", df2)                     

Yields below output.


After dropping multiple columns:
# Output:
            Courses
0             Spark
1             Spark
2           PySpark
3              JAVA
4            Hadoop
5              .Net
6            Python
7               AEM
8            Oracle
9           SQL DBA
10                C
11  WebTechnologies

Drop Columns of Index Using DataFrame.loc[] and drop() Methods

Similarly, to drop columns using DataFrame.loc[] and the drop() method, you specify the range of column labels you want to drop using loc[]. For instance, df.loc[:, Courses:Fee] select all rows (:) and columns from Courses to Fee using label-based indexing. .columns returns the column labels within the specified range. Then you can use df.drop() to drop the columns obtained from the previous step along the specified axis (axis=1 for columns).


# Drop columns of index 
# Using DataFrame.loc[] and drop() methods.
df2 = df.drop(df.loc[:, 'Courses':'Fee'].columns,axis = 1)
print("After dropping multiple columns:\n", df2)

# Drop columns of index 
# Using DataFrame.loc[] and drop() methods
columns_to_drop = df.loc[:, 'Courses':'Fee'].columns
df2 = df.drop(columns_to_drop, axis=1)
print("After dropping multiple columns:\n", df2)

Yields below output.


# Output:
   Duration
0    30days
1    35days
2    40days
3    45days
4    50days
5    55days
6    60days
7    35days
8    30days
9    40days
10   50days
11   55days

Complete Examples of Drop Columns By Index


# Create a Pandas DataFrame.
import pandas as pd
import numpy as np
technologies= {
    'Courses':["Spark","Spark","PySpark","JAVA","Hadoop",".Net","Python","AEM","Oracle","SQL DBA","C","WebTechnologies"],
    'Fee' :[22000,25000,23000,24000,26000,30000,27000,28000,35000,32000,20000,15000],
    'Duration':['30days','35days','40days','45days','50days','55days','60days','35days','30days','40days','50days','55days']
          }
df = pd.DataFrame(technologies)
print(df)

# Using DataFrame.drop() method.
df2=df.drop(df.columns[1], axis=1)
print(df2)

# Drop Multiple Columns by labels.
df2 = df.drop(['Courses', 'Duration'],axis = 1)
print(df2)
                    
# Drop columns based on column index.
df2 = df.drop(df.columns[[0, 1, 2]],axis = 1)
print(df2)

# Drop column by index using DataFrame.iloc[] and drop() methods.
df2 = df.drop(df.iloc[:, 1:3],axis = 1)
print(df2)

# Drop columns by labels using DataFrame.loc[] and drop() methods.
df2 = df.drop(df.loc[:, 'Courses':'Fee'].columns,axis = 1)
print(df2)

FAQ on Drop Columns by Index

How do I drop a single column by its index in a Pandas DataFrame?

Use the DataFrame.drop() method with the column index specified in the columns parameter and set the axis parameter to 1. For example: df.drop(columns=df.columns[index], axis=1).

How can I drop multiple non-contiguous columns by index at once?

You can drop multiple non-contiguous columns by specifying a list of column indexes within the df.columns accessor. For example, df = df.drop(df.columns[[0, 2, 4]], axis=1)

How can I remove multiple columns using their indices?

Provide a list of column indices to the columns parameter in the drop() method and set axis=1. For example: df.drop(columns=[df.columns[index1], df.columns[index2]], axis=1).

What if I want to drop columns by index using column names?

If you prefer to use column names instead of indexes, you can directly specify the column names within the drop() method. For example, df = df.drop(['column1′, ‘column3’], axis=1)

Will the DataFrame be modified in place when dropping columns by index?

By default, drop() does not modify the DataFrame in place. To modify the DataFrame in place, set the inplace parameter to True.

]]>
4377
Python CGI Programming https://shishirkant.com/python-cgi-programming/?utm_source=rss&utm_medium=rss&utm_campaign=python-cgi-programming Thu, 28 Sep 2023 15:11:08 +0000 https://shishirkant.com/?p=4312 The Concept of CGI

CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between a web application and the client application (or the browser). The programs based on CGI helps in communicating between the web servers and the client. Whenever the client browser makes a request, it sends it to the webserver, and the CGI programs return output to the webserver based on the input that the client-server provides.

Common Gateway Interface (CGI) provides a standard for peripheral gateway programs to interface with the data servers like an HTTP server.

The programming with CGI is written dynamically, which generates web-pages responding to the input from the user or the web-pages interacting with the software on the server.

The Concept of Web Browsing

Have you ever wondered how these blue-colored underlined texts, commonly known as hyperlinks, able to take you from one web-page or Uniform Resource Locator (URL) to another? What exactly happens when some user clicks on a hyperlink?

Let’s understand the very concept behind web browsing. Web browsing consists of some steps that are as follows:

STEP 1: Firstly, the browser communicates with the data server, say HTTP server, to demand the URL.

STEP 2: Once it is done, then it parses the URL.

STEP 3: After then, it checks for the specified filename.

STEP 4: Once it finds that file, a request is made and sent it back.

STEP 5: The Web browser accepts a response from the webserver.

STEP 6: As the server’s response, it can either display the requested file or a message showing error.

However, it may be possible to set up an HTTP server because whenever a file in a specific directory is requested, it is processed as a program rather than sending that file back. The output of that program is shown back to the browser. This function is also known as the Common Gateway Interface or abbreviated as CGI. These processed programs are known as CGI scripts, and they can be a C or C++ program, Shell Script, PERL Script, Python Script, etc.

The working of CGI

Whenever the client-server requests the webserver, the Common Gateway Interface (CGI) handles these requests using external script files. These script files can be written in any language, but the chief idea is to recover the data more efficiently and quickly. These scripts are then used to convert the recovered data into an HTML format that can send data to these web servers in HTML formatted page.

An architectural diagram representing the working of CGI is shown below:

Usage of cgi module

Python provides the cgi module consisting of numerous useful core properties. These properties and functions can be used by importing the cgi module, in current working program as shown below:

import cgi

Now, We will use cgitb.enable() in our script to stimulate an exception handler in the web browser to display the detailed report for the errors that occurred. The save will look as shown below:

import cgi

cgitb.enable()

Now, we can save the report with the help of the following script.

import cgitb 
cgitb.enable(display = 0, logdir = “/path/to/logdir” )

The function of the cgi module stated above would help throughout the script development. These reports help the user for debugging the script efficiently. Whenever the users get the expected result, they can eliminate this.

As we have discussed earlier, we can save information with the help of the form. But the problem is, how can we obtain that information? To answer this question, let’s understand the FieldStorage class of Python. If the form contains the non-ASCII characters, we can apply the encoding keyword parameter to the document. We will find the content <META> tag inside the <HEAD> section of the HTML file.

 The FieldStorage class is used to read the form data from the environment or the standard input.

FieldStorage instance is similar to the Python dictionary. The user can utilize the len() and all the dictionary functions as the FieldStorage instance. It is used to overlook the fields that have values as an empty string. The users can also consider the void values with the optional keyword parameter keep_blank_values by setting it to True.

Let’s see an example:

form = cgi.FieldStorage()   if ("name" not in form or "add" not in form):       
    print("<H1>Input Error!!</H1>")
   print("Please enter the details in the Name and Address fields!")    return 
print("<p>Name: file_item = form["userfile"]   
if (fileitem.file):      
    # It represents the uploaded file     
    count_line = 0       
    while(True):           
        line = fileitem.file.readline()   
        if not line: break           
        count_line = count_line + 1   # The execution of next lines of code will start here...

In the above snippet of code, we have utilized the form [“name”], where name is key, for extracting the value which the user enters.

To promptly fetch the string value, we can utilize the getvalue() method. This method also takes a second argument by default. And if the key is not available, it will return the value as default.

Moreover, if the information in the submitted form has multiple fields with the same name, we should take the help of the form.getlist() function. This function helps in returning the list of strings. Now let’s look at the following snippet of code; we have added some username fields and separate them by commas.

first_value = form.getlist("username")   f_username = ",".join(value)

If we want to access the field where a file is uploaded and read that in bytes, we can use the value attribute or the getvalue() method. Let’s see the following snippet of code if the user uploads the file.

file_item = form["userfile"]   
if (fileitem.file):      
    # It represents the uploaded file     
    count_line = 0       
    while(True):           
        line = fileitem.file.readline()           if not line: break           
        count_line = count_line + 1  

An error can often interrupt the program while reading the content of the file that was uploaded. It may happen when a user clicks on the Back Button or the Cancel Button. However, to set the value – 1, the FieldStorage class provides the done attribute.

Furthermore, the item will be objects of the MiniFieldStorage class if the submitted form is in the “old” format. The attributes like list, filename, and file are always None in this class.

Usually, the form is submitted with the POST method’s help and contains a query string with both the MiniFieldStorage and FieldStorage items.

Let’s see a list of the FieldStorage attribute in the following table.

FieldStorage Attributes:

S. No.AttributesDescription
1NameThe Name attribute is used to represent the field name.
2FileThe File attribute is used as a file(-like) instance to read data as bytes.
3FilenameThe Filename attribute is used to represent the filename at the Client-side.
4TypeThe Type attribute is used to show the type of content.
5ValueThe Value attribute is used to upload files, read the files and return byte. It is a string type value.
6HeaderThe Header attribute is used as a dictionary type instance containing all headers.

In addition to the above, the FieldStorage instance uses various core methods for manipulating users’ data. Some of them are listed below:

FieldStorage Methods:

S. No.MethodsDescription
1getfirst()The getfirst() method is used to return the received first value.
2getvalue()The getvalue() method is used as a dictionary get() method
3getlist()The getlist() method is used to return the list of values received.
4keys()The keys() method is used as the dictionary keys() method
5make_file()The make_file() method is used to return a writable and readable file.

CGI Program Structure in Python

Let’s understand the structure of a Python CGI Program:

  • There must be two sections that separate the output of the Python CGI script by a blank line.
  • The first section consists of the number of headers describing the client about the type of data used, and the other section consists of the data that will be displayed during the execution of the script.

Let’s have a look at the Python code given below:

print ("Content-type : text/html") 
# now enter the rest html document print ("<html>") 
print ("<head>") 
print ("<title> Welcome to CGI program </title>") 
print ("<head>") 
print ("<body>") 
print ("<h2> Hello World! This is my first CGI program. </h2>") print ("</body>") 
print ("</html>")

Now, let’s save the above file as cgi.py. Once we execute the file, we should see an output, as shown below:

Hello World! This is my first CGI program.

The above program is a simple Python script that writes the output to STDOUT file that is on-screen.

Understanding the HTTP Header

There are various HTTP headers defined that are frequently used in the CGI programs. Some of them are listed below:

S. No.HTTP HeaderDescription
1Content-typeThe Content-type is a MIME string used for defining the file format that is being returned.
2Content-length: NThe Content-length works as the information used for reporting the estimated time for downloading a file.
3Expires: DateThe Expires: Date is used for displaying the valid date information
4Last-modified: DateThe Last-modified: Date is used to show the resource’s last modification date
5Location: URLThe Location: URL is used to display the URL returned by the server.
6Set-Cookies: StringThe Set-Cookies: String is used for setting the cooking with help of a string

The CGI Environment Variables

There are some variables predefined in the CGI environment alongside the HTML syntax. Some of them are listed in the following table:

S. No.Environment VariablesDescription
1CONTENT_TYPEThe CONTENT_TYPE variable is used to describe the type and data of the content.
2CONTENT_LENGTHThe CONTENT_LENGTH variable is used to define the query or information length.
3HTTP_COOKIEThe HTTP_COOKIE variable is used to return the cookie set by the user in the current session.
4HTTP_USER_AGENTThe HTTP_USER_AGENT variable is used for displaying the browser’s type currently being used by the user.
5REMOTE_HOSTThe REMOTE_HOST variable is used for describing the Host-name of the user.
6PATH_INFOThe PATH_INFO variable is used for describing the CGI script path.
7REMOTE_ADDRThe REMOTE_ADDR variable is used for defining the IP address of the visitor.
8REQUEST_METHODThe REQUEST_METHOD variable is used for requests with the help of the GET or POST method.

How to Debug CGI Scripts?

Then, the test() function can be used from the script. We can write the following code using a single statement

cgi.test()

Pros and Cons of CGI Programming

Some Pros of CGI Programming:

There are numerous pros of using CGI programming. Some of them are as follows:

  • The CGI programs are multi-lingual. These programs can be used with any programming language.
  • The CGI programs are portable and can work on almost any web-server.
  • The CGI programs are quite scalable and can perform any task, whether it’s simple or complex.
  • The CGIs take lesser time in processing requests.
  • The CGIs can be used in development; they can reduce the cost of developments and maintenance, making it profitable.
  • The CGIs can be used for increasing the dynamic communication in web applications.

Some Cons of CGI Programming:

There are a few cons of using CGI programming. Some of them are as follows:

  • The CGI programs are pretty much complex, making it harder to debug.
  • While initiating the program, the interpreter has to appraise a CGI script in every initiation. As an output, it creates a lot of traffic because of multiple requests from the client-server’s side.
  • The CGI programs are fairly susceptible, as they are mostly free and easily available with no server security.
  • CGI utilizes a lot of time in processing.
  • The data doesn’t store in the cache memory during the loading of the page.
  • CGIs have huge extensive codebases, mostly in Perl.
]]>
4312
Python Regex Functions https://shishirkant.com/python-regex-functions/?utm_source=rss&utm_medium=rss&utm_campaign=python-regex-functions Thu, 28 Sep 2023 15:02:27 +0000 https://shishirkant.com/?p=4308 A regular expression is a set of characters with highly specialized syntax that we can use to find or match other characters or groups of characters. In short, regular expressions, or Regex, are widely used in the UNIX world.

Import the re Module

  1. # Importing re module  
  2. import re  

The re-module in Python gives full support for regular expressions of Pearl style. The re module raises the re.error exception whenever an error occurs while implementing or using a regular expression.

We’ll go over crucial functions utilized to deal with regular expressions.

But first, a minor point: many letters have a particular meaning when utilized in a regular expression called metacharacters.Backward Skip 10sPlay VideoForward Skip 10s

The majority of symbols and characters will easily match. (A case-insensitive feature can be enabled, allowing this RE to match Python or PYTHON.) For example, the regular expression ‘check’ will match exactly the string ‘check’.

There are some exceptions to this general rule; certain symbols are special metacharacters that don’t match. Rather, they indicate that they must compare something unusual or have an effect on other parts of the RE by recurring or modifying their meaning.

Metacharacters or Special Characters

As the name suggests, there are some characters with special meanings:

CharactersMeaning
.Dot – It matches any characters except the newline character.
^Caret – It is used to match the pattern from the start of the string. (Starts With)
$Dollar – It matches the end of the string before the new line character. (Ends with)
*Asterisk – It matches zero or more occurrences of a pattern.
+Plus – It is used when we want a pattern to match at least one.
?Question mark – It matches zero or one occurrence of a pattern.
{}Curly Braces – It matches the exactly specified number of occurrences of a pattern
[]Bracket – It defines the set of characters
|Pipe – It matches any of two defined patterns.

Special Sequences:

The ability to match different sets of symbols will be the first feature regular expressions can achieve that’s not previously achievable with string techniques. On the other hand, Regexes isn’t much of an improvement if that had been their only extra capacity. We can also define that some sections of the RE must be reiterated a specified number of times.

The first metacharacter we’ll examine for recurring occurrences is *. Instead of matching the actual character ‘*,’ * signals that the preceding letter can be matched 0 or even more times rather than exactly once.

Ba*t, for example, matches ‘bt’ (zero ‘a’ characters), ‘bat’ (one ‘a’ character), ‘baaat’ (three ‘a’ characters), etc.

Greedy repetitions, such as *, cause the matching algorithm to attempt to replicate the RE as many times as feasible. If later elements of the sequence fail to match, the matching algorithm will retry with lesser repetitions.

Special Sequences consist of ‘\’ followed by a character listed below. Each character has a different meaning.

CharacterMeaning
\dIt matches any digit and is equivalent to [0-9].
\DIt matches any non-digit character and is equivalent to [^0-9].
\sIt matches any white space character and is equivalent to [\t\n\r\f\v]
\SIt matches any character except the white space character and is equivalent to [^\t\n\r\f\v]
\wIt matches any alphanumeric character and is equivalent to [a-zA-Z0-9]
\WIt matches any characters except the alphanumeric character and is equivalent to [^a-zA-Z0-9]
\AIt matches the defined pattern at the start of the string.
\br”\bxt” – It matches the pattern at the beginning of a word in a string.
r”xt\b” – It matches the pattern at the end of a word in a string.
\BThis is the opposite of \b.
\ZIt returns a match object when the pattern is at the end of the string.

RegEx Functions:

  • compile – It is used to turn a regular pattern into an object of a regular expression that may be used in a number of ways for matching patterns in a string.
  • search – It is used to find the first occurrence of a regex pattern in a given string.
  • match – It starts matching the pattern at the beginning of the string.
  • fullmatch – It is used to match the whole string with a regex pattern.
  • split – It is used to split the pattern based on the regex pattern.
  • findall – It is used to find all non-overlapping patterns in a string. It returns a list of matched patterns.
  • finditer – It returns an iterator that yields match objects.
  • sub – It returns a string after substituting the first occurrence of the pattern by the replacement.
  • subn – It works the same as ‘sub’. It returns a tuple (new_string, num_of_substitution).
  • escape – It is used to escape special characters in a pattern.
  • purge – It is used to clear the regex expression cache.

1. re.compile(pattern, flags=0)

It is used to create a regular expression object that can be used to match patterns in a string.

Example:

# Importing re module  
import re  

# Defining regEx pattern  
pattern = "amazing"  

# Createing a regEx object
regex_object = re.compile(pattern)  

# String  
text = "This tutorial is amazing!"   

# Searching for the pattern in the string  
match_object = regex_object.search(text)  

# Output  
print("Match Object:", match_object)  


Output:
Match Object:

This is equivalent to:

re_obj = re.compile(pattern)
result = re_obj.search(string)
=result = re.search(pattern, string)

Note – When it comes to using regular expression objects several times, the re.complie() version of the program is much more efficient.

2. re.match(pattern, string, flags=0)

  • It starts matching the pattern from the beginning of the string.
  • Returns a match object if any match is found with information like start, end, span, etc.
  • Returns a NONE value in the case no match is found.

Parameters

  • pattern:-this is the expression that is to be matched. It must be a regular expression
  • string:-This is the string that will be compared to the pattern at the start of the string.
  • flags:-Bitwise OR (|) can be used to express multiple flags.

Example:

# Importing re module  
import re  

# Our pattern  
pattern = "hello"  

# Returns a match object if found else Null  
match = re.match(pattern, "hello world")  

print(match) # Printing the match object  
print("Span:", match.span()) # Return the tuple (start, end)  
print("Start:", match.start()) # Return the starting index  
print("End:", match.end()) # Returns the ending index  

Output: 
Span: (0, 5) 
Start: 0 
End: 5

Another example of the implementation of the re.match() method in Python.

  • The expressions “.w*” and “.w*?” will match words that have the letter “w,” and anything that does not has the letter “w” will be ignored.
  • The for loop is used in this Python re.match() illustration to inspect for matches for every element in the list of words.

CODE:

import re    
line = "Learn Python through tutorials on shishirkant"  
match_object = re.match( r'.w* (.w?) (.w*?)', line, re.M|re.I)

if match_object:    
    print ("match object group : ", match_object.group())   
    print ("match object 1 group : ", match_object.group(1))
    print ("match object 2 group : ", match_object.group(2))  
else:    
    print ( "There isn't any match!!" )   

Output:
There isn't any match!!

3. re.search(pattern, string, flags=0)

The re.search() function will look for the first occurrence of a regular expression sequence and deliver it. It will verify all rows of the supplied string, unlike Python’s re.match(). If the pattern is matched, the re.search() function produces a match object; otherwise, it returns “null.”

To execute the search() function, we must first import the Python re-module and afterward run the program. The “sequence” and “content” to check from our primary string are passed to the Python re.search() call.

Here is the description of the parameters –

pattern:- this is the expression that is to be matched. It must be a regular expression

string:- The string provided is the one that will be searched for the pattern wherever within it.

flags:- Bitwise OR (|) can be used to express multiple flags. These are modifications, and the table below lists them.

Code

import re  

line = "Learn Python through tutorials on shishirkant";  

search_object = re.search( r' .*t? (.*t?) (.*t?)', line) 
if search_object:  
    print("search object group : ", search_object.group())  
    print("search object group 1 : ", search_object.group(1)) 
    print("search object group 2 : ", search_object.group(2)) 
else:  
    print("Nothing found!!")  

Output:
search object group : Python through tutorials on shishirkant 
search object group 1 : on 
search object group 2 : shishirkant

4. re.sub(pattern, repl, string, count=0, flags=0)

  • It substitutes the matching pattern with the ‘repl’ in the string
  • Pattern – is simply a regex pattern to be matched
  • repl – repl stands for “replacement” which replaces the pattern in string.
  • Count – This parameter is used to control the number of substitutions

Example 1:

# Importing re module  
import re  

# Defining parameters  
pattern = "like" # to be replaced  
repl = "love" # Replacement  
text = "I like Shishirkant!" # String 

# Returns a new string with a substituted pattern 
new_text = re.sub(pattern, repl, text)  

# Output  
print("Original text:", text)  
print("Substituted text: ", new_text)  

Output:
Original text: I like Shishirkant! 
Substituted text: I love Shishirkant!

In the above example, the sub-function replaces the ‘like’ with ‘love’.

Example 2 – Substituting 3 occurrences of a pattern.

# Importing re package  
import re  

# Defining parameters  
pattern = "l" # to be replaced  
repl = "L" # Replacement  
text = "I like Shishirkant! I also like tutorials!" # String  

# Returns a new string with the substituted pattern  
new_text = re.sub(pattern, repl, text, 3)  

# Output  
print("Original text:", text)  
print("Substituted text:", new_text)  

Output:
Original text: I like Shishirkant! I also like tutorials! 
Substituted text: I Like Shishirkant! I aLso Like tutorials!

Here, first three occurrences of ‘l’ is substituted with the “L”.

5. re.subn(pattern, repl, string, count=0, flags=0)

  • Working of subn if same as sub-function
  • It returns a tuple (new_string, num_of_substitutions)

Example:

# Importing re module  
import re  

# Defining parameters  
pattern = "l" # to be replaced  
repl = "L" # Replacement  
text = "I like Shishirkant! I also like tutorials!" # String  

# Returns a new string with the substituted pattern  
new_text = re.subn(pattern, repl, text, 3)  

# Output  
print("Original text:", text)  
print("Substituted text:", new_text) 

Output:
Original text: I like Shishirkant! I also like tutorials! 
Substituted text: ('I Like Shishirkant! I aLso Like tutorials!', 3)

    In the above program, the subn function replaces the first three occurrences of ‘l’ with ‘L’ in the string.

    6. re.fullmatch(pattern, string, flags=0)

    • It matches the whole string with the pattern.
    • Returns a corresponding match object.
    • Returns None in case no match is found.
    • On the other hand, the search() function will only search the first occurrence that matches the pattern.

    Example:

    # Importing re module  
    import re   
    # Sample string  
    line = "Hello world";    
    
    # Using re.fullmatch()  
    print(re.fullmatch("Hello", line))  
    print(re.fullmatch("Hello world", line))  

    Output:

    None

    In the above program, only the ‘Hello world” has completely matched the pattern, not ‘Hello’.

    Q. When to use re.findall()?

    Ans. Suppose we have a line of text and want to get all of the occurrences from the content, so we use Python’s re.findall() function. It will search the entire content provided to it.

    7. re.finditer(pattern, string, flags=0)

    • Returns an iterator that yields all non-overlapping matches of pattern in a string.
    • String is scanned from left to right.
    • Returning matches in the order they were discovered

    # Importing re module  
    import re   
    
    # Sample string  
    line = "Hello world. I am Here!";  
    
    # Regex pattern  
    pattern = r'[aeiou]'  
    
    # Using re.finditer()  
    iter_ = re.finditer(pattern, line)  
    
    # Iterating the itre_  
    for i in iter_:  
        print(i)  

    Output:

    8. re.split(pattern, string, maxsplit=0, flags=0)

    • It splits the pattern by the occurrences of patterns.
    • If maxsplit is zero, then the maximum number of splits occurs.
    • If maxsplit is one, then it splits the string by the first occurrence of the pattern and returns the remaining string as a final result.

    Example:

    # Import re module  
    import re    
    
    # Pattern  
    pattern = ' '  
    
    # Sample string  
    line = "Learn Python through tutorials on shishirkant"    
    
    # Using split function to split the string after ' '  
    result = re.split( pattern, line)   
    
    # Printing the result  
    print("When maxsplit = 0, result:", result)  
    
    # When Maxsplit is one  
    result = re.split(pattern, line, maxsplit=1)  
    print("When maxsplit = 1, result =", result)
    
    Output:
    When maxsplit = 0, result: ['Learn', 'Python', 'through', 'tutorials', 'on', 'shishirkant'] 
    When maxsplit = 1, result = ['Learn', 'Python through tutorials on shishirkant']

    9. re.escape(pattern)

    • It escapes the special character in the pattern.
    • The esacpe function become more important when the string contains regular expression metacharacters in it.

    Example:

    # Import re module  
    import re    
    
    # Pattern  
    pattern = 'https://www.shishirkant.com/'  
    
    # Using escape function to escape metacharacters  
    result = re.escape( pattern)   
      
    # Printing the result  
    print("Result:", result)

      Output:Result: https://www\.shishirkant\.com/

      The escape function escapes the metacharacter ‘.’ from the pattern. This is useful when want to treat metacharacters as regular characters to match the actual characters themselves.

      10. re.purge()

      • The purge function does not take any argument that simply clears the regular expression cache.

      Example:

      # Importing re module  
      import re  
      
      # Define some regular expressions  
      pattern1 = r'\d+'  
      pattern2 = r'[a-z]+'  
      
      # Use the regular expressions  
      print(re.search(pattern1, '123abc'))  
      print(re.search(pattern2, '123abc'))  
      
      # Clear the regular expression cache  
      re.purge()  
      
      # Use the regular expressions again  
      print(re.search(pattern1, '456def'))  
      print(re.search(pattern2, '456def'))

          Output:

          • After using, pattern1 and pattern2 to search for matches in the string ‘123abc’.
          • We have cleared the cache using re.purge().
          • We have again used pattern1 and pattern2 to search for matches in the string ‘456def’.
          • Since the regular expression cache has been cleared. The regular expressions are recompiled, and searching for matches in the ‘456def’ has been performed with the new regular expression object.

          Matching Versus Searching – re.match() vs. re.search()

          Python has two primary regular expression functions: match and search. The match function looks for a match only where the string starts, whereas the search function looks for a match everywhere in the string.

          CODE:

          # Import re module  
          import re
          
          # Sample string  
          line = "Learn Python through tutorials on shishirkant" 
          
          # Using match function to match 'through'
          match_object = re.match( r'through', line, re.M|re.I)
          if match_object:    
              print("match object group : ", match_object)    
          else:    
              print( "There isn't any match!!")    
          
          # using search function to search  
          search_object = re.search( r'through', line, re.M|re.I)    
          if search_object:    
              print("Search object group : ", search_object)    
          else:    
              print("Nothing found!!")  
          
          Output:
          There isn't any match!! 
          Search object group :

          The match function checks whether the string is starting with ‘through’ or not, and the search function checks whether there is ‘through’ in the string or not.

          ]]>
          4308
          Python Regular Expressions – I https://shishirkant.com/python-regular-expressions-i/?utm_source=rss&utm_medium=rss&utm_campaign=python-regular-expressions-i Thu, 28 Sep 2023 06:06:58 +0000 https://shishirkant.com/?p=4305 Introduction to the Python regular expressions

          Regular expressions (called regex or regexp) specify search patterns. Typical examples of regular expressions are the patterns for matching email addresses, phone numbers, and credit card numbers.

          Regular expressions are essentially a specialized programming language embedded in Python. And you can interact with regular expressions via the built-in re module in Python.

          The following shows an example of a simple regular expression:

          '\d'

          Code language: Python (python)

          In this example, a regular expression is a string that contains a search pattern. The '\d' is a digit character set that matches any single digit from 0 to 9.

          Note that you’ll learn how to construct more complex and advanced patterns in the next tutorials. This tutorial focuses on the functions that deal with regular expressions.

          To use this regular expression, you follow these steps:

          First, import the re module:

          import re

          Second, compile the regular expression into a Pattern object:

          p = re.compile('\d')

          Third, use one of the methods of the Pattern object to match a string:

          s = "Python 3.10 was released on October 04, 2021" 
          result = p.findall(s) 
          
          print(result)

          Output:

          ['3', '1', '0', '0', '4', '2', '0', '2', '1']

          The findall() method returns a list of single digits in the string s.

          The following shows the complete program:

          import re 
          
          p = re.compile('\d') 
          s = "Python 3.10 was released on October 04, 2021" 
          
          results = p.findall(s) 
          print(results)

          Besides the findall() method, the Pattern object has other essential methods that allow you to match a string:

          MethodPurpose
          match()Find the pattern at the beginning of a string
          search()Return the first match of a pattern in a string
          findall()Return all matches of a pattern in a string
          finditer()Return all matches of a pattern as an iterator

          Python regular expression functions

          Besides the Pattern class, the re module has some functions that match a string for a pattern:

          • match()
          • search()
          • findall()
          • finditer()

          These functions have the same names as the methods of the Pattern object. Also, they take the same arguments as the corresponding methods of the Pattern object. However, you don’t have to manually compile the regular expression before using it.

          The following example shows the same program that uses the findall() function instead of the findall() method of a Pattern object:

          import re 
          
          s = "Python 3.10 was released on October 04, 2021." 
          results = re.findall('\d',s) 
          print(results)

          Using the functions in the re module is more concise than the methods of the Pattern object because you don’t have to compile regular expressions manually.

          Under the hood, these functions create a Pattern object and call the appropriate method on it. They also store the compiled regular expression in a cache for speed optimization.

          It means that if you call the same regular expression from the second time, these functions will not need to recompile the regular expression. Instead, they get the compiled regular expression from the cache.

          Should you use the re functions or methods of the Pattern object?

          If you use a regular expression within a loop, the Pattern object may save a few function calls. However, if you use it outside of loops, the difference is very little due to the internal cache.

          The following sections discuss the most commonly used functions in the re module including search()match(), and fullmatch().

          search() function

          The search() function searches for a pattern within a string. If there is a match, it returns the first Match object or None otherwise. For example:

          import re 
          
          s = "Python 3.10 was released on October 04, 2021." 
          pattern = '\d{2}' 
          match = re.search(pattern, s) 
          print(type(match)) 
          print(match)
          Output:<class 're.Match'> 
          <re.Match object; span=(9, 11), match='10'>

          In this example, the search() function returns the first two digits in the string s as the Match object.

          Match object

          The Match object provides the information about the matched string. It has the following important methods:

          MethodDescription
          group()Return the matched string
          start()Return the starting position of the match
          end()Return the ending position of the match
          span()Return a tuple (start, end) that specifies the positions of the match

          The following example examines the Match object:

          import re 
          
          s = "Python 3.10 was released on October 04, 2021." 
          result = re.search('\d', s) 
          
          print('Matched string:',result.group()) 
          print('Starting position:', result.start()) 
          print('Ending position:',result.end()) print('Positions:',result.span())

          Output:

          Matched string: 3 
          Starting position: 7 
          Ending position: 8 
          Positions: (7, 8)

          match() function

          The match() function returns a Match object if it finds a pattern at the beginning of a string. For example:

          import re 
          
          l = ['Python', 
               'CPython is an implementation of Python written in C', 
               'Jython is a Java implementation of Python', 
                'IronPython is Python on .NET framework'] 
          
          pattern = '\wython' 
          for s in l: 
              result = re.match(pattern,s) 
              print(result)

          Output:

          <re.Match object; span=(0, 6), match='Python'> 
          None 
          <re.Match object; span=(0, 6), match='Jython'> 
          None

          In this example, the \w is the word character set that matches any single character.

          The \wython matches any string that starts with any sing word character and is followed by the literal string ython, for example, Python.

          Since the match() function only finds the pattern at the beginning of a string, the following strings match the pattern:

          Python 
          Jython is a Java implementation of Python

          And the following string doesn’t match:

          'CPython is an implementation of Python written in C' 
          'IronPython is Python on .NET framework'

          fullmatch() function

          The fullmatch() function returns a Match object if the whole string matches a pattern or None otherwise. The following example uses the fullmatch() function to match a string with four digits:

          import re 
          
          s = "2021" 
          pattern = '\d{4}' 
          result = re.fullmatch(pattern, s) 
          print(result)

          Output:

          <re.Match object; span=(0, 4), match='2019'>(python)

          The pattern '\d{4}' matches a string with four digits. Therefore, the fullmatch() function returns the string 2021.

          If you place the number 2021 at the middle or the end of the string, the fullmatch() will return None. For example:

          import re 
          
          s = "Python 3.10 released in 2021" 
          pattern = '\d{4}' 
          result = re.fullmatch(pattern, s) 
          print(result)

          Output:

          None

          Regular expressions and raw strings

          It’s important to note that Python and regular expression are different programming languages. They have their own syntaxes.

          The re module is the interface between Python and regular expression programming languages. It behaves like an interpreter between them.

          To construct a pattern, regular expressions often use a backslash '\' for example \d and \w . But this collides with Python’s usage of the backslash for the same purpose in string literals.

          For example, suppose you need to match the following string:

          s = '\section'

          In Python, the backslash (\) is a special character. To construct a regular expression, you need to escape any backslashes by preceding each of them with a backslash (\):

          pattern = '\\section'Code language: JavaScript (javascript)

          In regular expressions, the pattern must be '\\section'. However, to express this pattern in a string literal in Python, you need to use two more backslashes to escape both backslashes again:

          pattern = '\\\\section'Code language: JavaScript (javascript)

          Simply put, to match a literal backslash ('\'), you have to write '\\\\' because the regular expression must be '\\' and each backslash must be expressed as '\\' inside a string literal in Python.

          This results in lots of repeated backslashes. Hence, it makes the regular expressions difficult to read and understand.

          A solution is to use the raw strings in Python for regular expressions because raw strings treat the backslash (\) as a literal character, not a special character.

          To turn a regular string into a raw string, you prefix it with the letter r or R. For example:

          import re 
          
          s = '\section' 
          pattern = r'\\section' 
          result = re.findall(pattern, s) 
          
          print(result) 
          Output:['\\section']

          Note that in Python ‘\section’ and ‘\\section’ are the same:

          p1 = '\\section' 
          p2 = '\section' 
          
          print(p1==p2) # true

          In practice, you’ll find the regular expressions constructed in Python using the raw strings.

          Summary

          • A regular expression is a string that contains the special characters for matching a string with a pattern.
          • Use the Pattern object or functions in re module to search for a pattern in a string.
          • Use raw strings to construct regular expression to avoid escaping the backslashes.
          ]]>
          4305
          Tkinter Themes https://shishirkant.com/tkinter-themes/?utm_source=rss&utm_medium=rss&utm_campaign=tkinter-themes Mon, 17 Apr 2023 14:09:35 +0000 https://shishirkant.com/?p=3615 Introduction to Tkinter ttk themes

          In Tkinter, a theme determines the “look & feel” of all the widgets. It’s a collection of styles for all the ttk widgets.

          A style specifies the appearance of a widget class e.g., a Button. Each theme comes with a set of styles. It’s possible to change the appearance of widgets by:

          • Modifying the built-in styles
          • or creatting new styles

          Tkinter allows you to change the current theme to another. When you change the current theme to a new one, Tkinter will apply the styles of that theme to all the ttk widgets.

          To get the available themes, you use the theme_names() method of the ttk.Style instance.

          First, create a new instance of the ttk.Style class:

          style = ttk.Style(root)Code language: Python (python)

          Second, get the available themes by calling the theme_names() method:

          style.theme_names()Code language: Python (python)

          To get the current theme, you use the theme_use() method:

          current_theme = style.theme_use()Code language: Python (python)

          Note that every operating system (OS) such as Windows, macOS, and Linux comes with its own predefined themes. If you use the theme_names() and theme_use() methods on different OS, you’ll get different results.

          To change the current theme to a new one, you pass the new theme name to the theme_use() method:

          style.theme_use(theme_name)Code language: Python (python)

          The following program shows all themes in your system and allows you to change one theme to another:

          import tkinter as tk
          from tkinter import ttk
          
          
          class App(tk.Tk):
              def __init__(self):
                  super().__init__()
          
                  # root window
                  self.title('Theme Demo')
                  self.geometry('400x300')
                  self.style = ttk.Style(self)
          
                  # label
                  label = ttk.Label(self, text='Name:')
                  label.grid(column=0, row=0, padx=10, pady=10,  sticky='w')
                  # entry
                  textbox = ttk.Entry(self)
                  textbox.grid(column=1, row=0, padx=10, pady=10,  sticky='w')
                  # button
                  btn = ttk.Button(self, text='Show')
                  btn.grid(column=2, row=0, padx=10, pady=10,  sticky='w')
          
                  # radio button
                  self.selected_theme = tk.StringVar()
                  theme_frame = ttk.LabelFrame(self, text='Themes')
                  theme_frame.grid(padx=10, pady=10, ipadx=20, ipady=20, sticky='w')
          
                  for theme_name in self.style.theme_names():
                      rb = ttk.Radiobutton(
                          theme_frame,
                          text=theme_name,
                          value=theme_name,
                          variable=self.selected_theme,
                          command=self.change_theme)
                      rb.pack(expand=True, fill='both')
          
              def change_theme(self):
                  self.style.theme_use(self.selected_theme.get())
          
          
          if __name__ == "__main__":
              app = App()
              app.mainloop()
          Code language: Python (python)

          In this example, when you select a theme from the radio button list, the change_theme() method will apply the selected theme.

          If you run the program on Windows 10, you’ll see the following window:

          Tkinter Theme

          If you change the theme to classic, you’ll see the style of the widgets (Label, Entry, Button, LabelFrame, and Radio Button) change to the following:

          ttk Theme

          Summary

          • Create an instance of the ttk.Style class to access the style database.
          • Use the style.theme_names() method to get available themes from the Operating System on which the Tkinter application is running.
          • Use the style.theme_use() method to change the current theme to a new one.
          ]]>
          3615
          NumPy asarray() function https://shishirkant.com/numpy-asarray-function/?utm_source=rss&utm_medium=rss&utm_campaign=numpy-asarray-function Thu, 13 Apr 2023 06:50:25 +0000 https://shishirkant.com/?p=3253 The numpy.asarray() function in Numpy is used to convert the input or any existing data into an array.

          • The existing data can be in the form of Lists, Tuples, tuples of tuples, list of tuples, tuples of lists, etc.
          • In case if you want to convert any python sequence into the Numpy array object i.e ndarray then this function is helpful for you.

          Syntax of numpy.asarray():

          Given below is the basic syntax to use this function:

          numpy.asarray(sequence,  dtype, order)  

          Parameters:

          Let us discuss the parameters mentioned above for the asarray() function:

          • sequence
            This parameter is used to indicate the input data that can be in any form and is to be converted into an array. This parameter includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
          • dtype
            This parameter is used to indicate the data type of each item of the array. It is an optional parameter with default value None.
          • order
            This parameter is used to indicate the memory representation that is whether to use row-major (C-style) or column-major (Fortran-style) The default value is set to ‘C’.

          Returned Values:

          This function will return an array with all the values from the sequence used to create the array. If the input is already an ndarray with matching dtype and order then this function will not create any copy.

          Now it’s time to take a look at some examples of this function.

          Example 1:

          In the code snippet given below we will convert a Python list into an array:

          import numpy as np
          
          mylist = [1, 2,4,5,8,10]
          np.asarray(mylist)

          Output:


          array([ 1, 2, 4, 5, 8, 10])

          Example 2:

          In the code snippet below we will create a NumPy array from a Python tuple:

          import numpy as np  
          
          inp = (10,9,1,2,3,4,5,6,7,8)     
          a = np.asarray(inp); 
          print("The output is:")
          print(a)  
          print("The datatype of output is:")
          print(type(a))  

          Output:


          The output is:
          [10 9 1 2 3 4 5 6 7 8]
          The datatype of output is:
          <class 'numpy.ndarray'>

          Example 3:

          In the code snippet given below we will create an array using more than one list:

          import numpy as np  
          
          l = [[1,2,3,4,5,6,7],[8,9],[12,34,45]]  
          a = np.asarray(l);
          print("The data type of output is:")
          print(type(a))  
          print("The output array is:")
          print(a)  

          Output:


          The data type of output is:
          <class 'numpy.ndarray'>
          The output array is:
          [list([1, 2, 3, 4, 5, 6, 7]) list([8, 9]) list([12, 34, 45])]
          ]]>
          3253
          Indian Business Strategy https://shishirkant.com/indian-business-strategy/?utm_source=rss&utm_medium=rss&utm_campaign=indian-business-strategy Fri, 05 Jun 2020 15:00:55 +0000 http://shishirkant.com/?p=1827 Business demand Passion and Patience. Without these two qualities, we cannot stand for any business. Passion is a key to small business owners for long term success. It really is endless energy. You have to get up early, work late. It takes lot of passion, a lot of energy and it takes a lot of you. On other hand, Patience may be more important than passion, because no businessman can succeed without it, without patience, millions of small business owners might never launched their companies. Many people have great ideas, or want to start their own business, nut few have the patience and passion. Patience is a key quality is networking and building the kinds of relationships that help to take to the next level of ideas.

          In India, every year millions of entrepreneurs come up with great ideas but most of go to fail because of no business and no strategic plans. Today, India stands as one of the largest contributors to global economy and suitable business or manufacturing place for foreign companies’ Indian government has been consistent in supporting business sector improvement through Liberalization, tax ratification or open approach towards foreign investments. But in India, every state as compare as individual country because of regional differences in language, talent, culture, infrastructure and wealth etc. for example South India is order with high talent, capabilities and more skilled population, on other hand North India is relatively poor as compare to South India in various streams. So, we have to make policy or plans according to state’s culture, talent and resources availability in their areas. So , before starting business, we have to insured who are our target audience . After that, our policy analyzing market’s size, growth, Industry Clusters and market stability. (Industry Cluster measure size of potentials customers for B2B and B2C companies, Market stability measure institutional, business and social stability)

          If you are planning to enter market, you need to creative strategies, identifying potential and developing a fair knowledge of the market. It is very important to develop a basic knowledge of the potential market. This process should be supported by a sound market entry strategy. But Job does not end here, it require proper implementation also for desired results in form of products and services.

          Now we shall discuss on Operation Management which is next level of business. It is the business function responsible for managing the process of creation of goods / products and services. It involves planning, organizing, coordinating and controlling all the resources needed to produce a company’s products and services. Operational Management for production and distribution are managing purchases, inventory control, quality control, storage, logistics and etc. In term of service organization, these can be customer care, banked services. IT support, store, distribution, security, facility maintenance etc. They have separate department for all activities. But many businessmen fail to operate that because of lack of knowledge of that management and no basic knowledge and strategy for that.

          It is not enough to the information about sale, inventory status and rest of detail your business. We must be an ability to analyze that information so we can evaluate what progress or situation in the past, understand what happening now and we can accurately process what goals in the future.

          Now, we shall discuss on Indian Marketing Mindset. Indian mindset takes a swing when it comes to marketing. It goes without saying, only launching new great quality product is not enough. The s\customers need something more information of the product, basically a reason to buy the product and only great quality is not going to help. In developed market, customers focus on product’s quality but in Indian market, customers focus on pricing of the products. 70% of Indian population lives in rural areas, where people find it easier to buy products as per their needs. Many purchase pouches of shampoo, conditional, detergents and even hair oil only when they need it and this form of packaging makes it cheap and convenient for them to use it. There are many options of advertising in the market these days. From electronics gadgets to fashion, a hundred of products listed to customers everyday via offline-online ads, TV ads and FM. Considering this what makes your brand different and memorable to the customers? Main marketing game starts now – the play the game of emotional content. Marketing campaign plays on human emotions which has great impact to the brands. Such emotional campaigns hold many takeaways in terms of storytelling and connections.

          India is a diverse consumer market. Many of business in India focus on brand awareness and letting the customers know about the product. But in local business, they focus on consumer tastes, cultural background, different level of affluence and superiority. Thus creating brand awareness is a crucial marketing strategy for any business functioning in India.

          The conclusion is, to enter the Indian market; we would require multiple marketing efforts that address differing regional opportunities, languages, cultural differences, standards, and levels of economic development.


          Shishir Kant Singh

          ]]>
          1827
          ख़ुशी https://shishirkant.com/%e0%a4%96%e0%a4%bc%e0%a5%81%e0%a4%b6%e0%a5%80/?utm_source=rss&utm_medium=rss&utm_campaign=%25e0%25a4%2596%25e0%25a4%25bc%25e0%25a5%2581%25e0%25a4%25b6%25e0%25a5%2580 Fri, 05 Jun 2020 14:10:53 +0000 http://shishirkant.com/?p=1819 ख़ुशी एक व्यवस्था है जो हमें सकारात्मकता की ओर ले जाती  है। जब हम किसी चीज़ को महसूस करते हैं तो  वो एक ख़ुशी  का बोध करती है, चाहे चीज़ पैसा हो, प्यार हो, संस्कार हो, इज़्ज़त हो इत्यादि। हाँ, ख़ुशी  और हंसी को मैं एक सामान नहीं मनाता, क्योंकि ख़ुशी हमारी इच्छाओँ पर केंद्रित होती हैं और हंसी हमारी भावनाओं पर। हमारी भावनाएं किसी चुटकुले पर, किसी मज़ाक पर , किसी के उपहास यदि पर ज्यादा हंसी देती है जो की एक क्षणिक अनुभव होता है।  इच्छाएँ असीमित होती हैं, इच्छाओँ  को वश में रखना भी बहुत जरुरी है। अपनी संतुष्टि के अनुसार इच्छाओँ  पर कार्य करना चाहिए।  धीरे धीरे इच्छाओँ को पूर्ण करके आगे की इच्छाओँ पर कार्य करना चाहिए, जिससे आपकी ख़ुशी का धरातल हमेशा बुनियादी रहेगा।  जरुरत तो हमें सकारत्मक रवैया रखने की है जिससे हम हमेशा संतुष्टि का अनुभव कर सकते हैं।

          हम ऐसे मौकों से भी गुजरते हैं जहाँ हम अपने को बहुत टुटा हुआ या असफल व्यक्ति महसूस करते हैं, तब जब एक उम्मीद की कोई किरण सिर्फ सुनाई देने से ही हमारे अंदर एक ख़ुशी महसूस होने लगती है , ये क्षण हमको  ऐसा प्रतीत होता है की दुःख के बाद सुख जरूर आता है।  ये तो सिर्फ सुनाई देने मात्र की अवस्था है, कहीं वो किरण हमारे दुःख दूर करने लगे तो स्वतः ही ख़ुशी एक साकारत्मक सोच में बदल जाती है और हमारे अंदर भी सभी नकारात्मकता का गमन होने लगता है।   नकारात्मकता सिर्फ हमें उदासीनता की ओर आकर्षित करती है।  हम जैसा सोचते हैं और जैसा व्यहवार करते हैं वही घूम कर हमारे पास आता है। दूसरों के साथ खुशियां बांटने में हम खुद के अंदर ख़ुशी को महसूस करते हैं। यदि हम दूसरों को बुरी लगने वाली बातों को नज़रअंदाज़ कर दें और सिर्फ ये कल्पना करें की मैं बहुत की खुशनसीब इंसान हूँ, तो सदैव हम खुश रहेंगे , बस केवल एक सकारात्मक सोच और व्यहवार अपनाने की जरुरत है।  इसके साथ हमको अपनी स्वार्थी  इच्छाओँ को भी त्यागना होगा , क्योंकि हम हमेशा श्रेष्ठ नहीं हैं।

          अपनी इच्छाओँ को समझना और उसके बाद अपनी योग्यता और सामर्थ्य पर भी गहन अध्ययन करना चाहिए, क्योंकि हमारे पास कई विकल्प रहते हैं , लेकिन एक समय एक विकल्प चुनना होता है तो हमको हमारी प्राथमिकता पर ध्यान देना चाहिए।  तभी ख़ुशी को आनन्दित किया जा सकता है। हमारी  प्राथमिकता परीक्षा में आने वाले बहुविकल्पी प्रश्रों की तरह हैं यदि गलत विकल्प चुना तो उसका दंड दुःख के रूप में मिलता है।  तो ये हमको तय करना होता है की किसे पाकर हम खुश हो सकते हैं।  जो चीज़ हमारे बस में नहीं है और उसको अपनी इच्छाशक्ति को अपार करके भी नहीं प् सकते, उसके लिए दुखी होना निरथ्य है।  हम जिसको बदल नहीं सकते, उसको स्वीकार करना ही हमारे लिए बेहतर है।  कभी हम सब संसारिक मोह की उलझनों में फँस जाते हैं, तब हम अपने मनोवैज्ञानिक शब्द को अपने जीवन में पाते हैं, जो इसको समझ गया या अपना लिया वो हर क्षेत्र और हर अवस्था को संभाल लेता है। जैसे की मज़ाक में बोला जाये तो हर नर-नारी अपने जीवनसाथी के रूप में हीरो-हेरोइन जैसा सुंदरता चाहता है लेकिन सच्चाई इसकी उल्ट होती है।  शादी होने के बाद जैसा भी जीवनसाथी या जीवनसाथिनी हो, अपनाना ही पड़ेगा और हमें उसकी हर गलती को हंसकर टालना भी होगा, ये ही ख़ुशी है , क्योंकि ये सब दीर्घकालिक ख़ुशी के लिए बहुत जरुरी है।

          त्वरित ख़ुशी और लम्बे समय की ख़ुशी में अंतर है। त्वरित शब्द से समझ आ रहा होगा की ये क्षणिक ख़ुशी होती है जो की थोड़े समय के लिए मन में उल्लास ला देती है , जैसे की बच्चों को उनके मन मुताबिक बॉक्स मिल जाना , स्कूल में किसी पीरियड में मास्टर का न आना , या ऑफिस में काम करने वाले व्यक्ति को छुट्टी मिल जाना, किसी को कोई उपहार मिल जाना इत्यादि , ये  सब एक त्वरित ख़ुशी है क्योंकि इसके बाद के पीरियड में मास्टर आएंगे , ऑफिस वाला व्यक्ति अगले दिन ज्यादा काम करेगा , उपहार वाला व्यक्ति भी बदले में कोई उपहार देने के बारे में सोचेगा।  बहुत  से अंतहीन उदाहरण है त्वरित ख़ुशी के।  इसे ऐसे कहें की त्वरित ख़ुशी  एक पल का आनंद है  जो मनुष्य पल  भर के लिए आनंदित होता है।  इसको पाने के लिए मनुष्य को कोई मेहनत नहीं करनी पड़ती है।

          जबकि लम्बे समय की ख़ुशी की  बात करें  तो इसके लिए मनुष्य को मेहनत करनी पड़ती है।  जैसा की  आप कोई परीक्षा (नौकरी)  पास करते  हैं तो  इसका प्रभाव लम्बे  समय तक ख़ुशी देता है, जबकि इसको पाने के लिए आपने कई बाधाओं को पार किया होगा, लेकिन नौकरी की ख़ुशी आपको इन बाधाओं पर विजय दर्शाती है।  ख़ुशी महसूस करने में बहुत समय और प्रयास लगता है। व्यापार करने वाला व्यक्ति बहुत हानि – लाभ देखता है , लेकिन उसकी लगन और प्रयास उसको  एक सफल व्यापारी बनाता है , ये अहसास उसको जीवन भर ख़ुशी में दिखती है।  तो हमको हमेशा लम्बी अवधि की ख़ुशी को प्राथमिकता देनी चाहिए जिसका हमारे परिवार पर भी एक प्रभाव  पड़ता है।

          ख़ुशी को महसूस करना  और हासिल करना , सब हमारे हाथ में होता है।  ख़ुशी, संतुष्टि और आनंद सब हमारे भीतर ही छुपा हुआ है, जरुरत है केवल उसे पहचानने  की।  इससे कोई फर्क नहीं पड़ना चाहिए की हम कौन है और किस अवस्था में हैं। यदि हम चाहें तो सकारात्मक सोच से ख़ुशी को अपने अंदर ही महसूस कर सकते हैं।


          शिशिर कान्त सिंह

          ]]>
          1819
          इंसान की फितरत https://shishirkant.com/%e0%a4%87%e0%a4%82%e0%a4%b8%e0%a4%be%e0%a4%a8-%e0%a4%95%e0%a5%80-%e0%a4%ab%e0%a4%bf%e0%a4%a4%e0%a4%b0%e0%a4%a4/?utm_source=rss&utm_medium=rss&utm_campaign=%25e0%25a4%2587%25e0%25a4%2582%25e0%25a4%25b8%25e0%25a4%25be%25e0%25a4%25a8-%25e0%25a4%2595%25e0%25a5%2580-%25e0%25a4%25ab%25e0%25a4%25bf%25e0%25a4%25a4%25e0%25a4%25b0%25e0%25a4%25a4 Fri, 05 Jun 2020 14:05:57 +0000 http://shishirkant.com/?p=1816 इंसान की फितरत को समझना इतना आसान नहीं है , क्योंकि जो उसका स्वार्थ है वही उसको  अच्छा या बुरे की क्षेणी में खड़ा करता है।  किसी को अच्छा या बुरा हम अपने मन की ख़ुशी से देखते हैं न की आत्मा की नज़र से।  क्योंकि आत्मा न्याय की वो अन्धी देवी है जिसमें प्यार और स्नेह नहीं होता है जबकि मन एक विचलित प्राणी है जो सिर्फ अपने को खुश और दूसरे को दुखी देखना चाहता है। इसलिए मनुष्य की फितरत  एक स्वार्थ को  जन्म देती है। स्वार्थ  अच्छे  भी होते हैं और बुरे भी।  जब इंसान पक्षियों को दाना या पानी देता है तो वो भी एक तरह का स्वार्थ है, क्योंकि वो चाहता है की हमारा पर्यावरण जीवित रहे।  जब हम अपने माता-पिता या बड़े को अपने आस-पास देखने की कोसिस करते हैं तो हम अपनी फितरत के अनुसार चाहते हैं की वो हमें समाज में रहने का सलीका सिखाएं।  क्योंकि समाज एक ऐसी जगह है की जहाँ फर कोई अपने को समाहित नहीं कर पता है जिससे उसका आचरण और दूसरों के तरीके में बहुत विभिन्नता आ जाती है।

          जब हम किसी को स्पर्श करते हैं तो हमारा स्पर्श करने का तरीका हमारी फितरत को परिभाषित करता है. मनुष्य के सुख-दुःख में ही इंसानी नियत को देखा  जा सकता है, जब इंसान खुश होता है तो बाकी इंसान उसको मूर्ख प्रतीत होते हैं , और जब वही इंसान देखि होता है तो वो उन्ही मूर्ख प्रतीत व्यक्तियों से उम्मीद की आशा संजोय रहता है। हमारा आचरण कोई जन्मजात नहीं है, ये समय और माहौल के हिसाब से अपने को संगठित करता है और दुसरो से भी वही संगठित होने की लालसा करता है, जबकि इंसान कोई रोबोट नहीं है जो  कोई प्रोग्रामिंग से चलता हो, इंसान तो अनन्तः है जिसका कोई भी सिरा नहीं है। आत्मा कभी किसी का गलत नहीं चाहती है, लेकिन मन का विस्तार आत्मा की सेना को धराशायी करता है, जिससे मनुष्य धोखा देना, चोरी करना , गलत काम करने जैसे संसार में कदम रखता है। किसी  को जानबूझकर दिया हुआ धोखा , चोरी करना और गलत काम से भी ज्यादा पापी है, क्योंकि तब आप सामने वाले के संस्कार को अपने राक्षस जैसे दिमाग से हराते हैं। वैसे भी हमारे ग्रंथो में राक्षस को हमेशा पाई माना गया है।  आज भी उनकी प्रवृति कुछ इंसानो में दिखती है। बात ये भी सही है की कोई फितरत किसी को थोपी हुई वस्तु नहीं है जो बारी-बारी से सभी उसको प्रयोग में लाते हैं, ये तो ऐसी चीज़ है जिसको बदलना मतलब कुत्ते की पूँछ सीधा करने जैसा सरीखा है।

          आज के संसारिक मोह माया में कोई किसी का भला जल्दी नहीं चाहता है, और जो किसी का भला चाहता है तो उनसे बहुत दुःख देखें होंगे जिसको सोचकर उसकी आत्मा कहती होगी की उसको वो दिन देखने से बचा लो।  जिसने आत्मा  की बात सुनी वो तो अपने को समाज में रहने का एक प्रतिष्ठ स्थान पा लेगा , अन्यथा मन की फितरत से  आदमी  कभी भी शांतचित नहीं रह सकता और विचारों के खेल में वो गलत  श्रेणी में स्थान  लेता जाता है।  आपके विचार आपको सही स्थान की ओर ले जाना चाहती है लेकिन आपकी फितरत आपको या तो अच्छा ले जाएगी या बुरा ले जाएगी।

          इसलिए मनुष्य को अपनी फितरत को जांचने के लिए अपनी आत्मा की वाणी सुननी चाहिए की आप सही कर रहे हैं या गलत।


          शिशिर कान्त सिंह

          ]]>
          1816
          कोरोना और विश्व अर्थव्यवस्था https://shishirkant.com/%e0%a4%95%e0%a5%8b%e0%a4%b0%e0%a5%8b%e0%a4%a8%e0%a4%be-%e0%a4%94%e0%a4%b0-%e0%a4%b5%e0%a4%bf%e0%a4%b6%e0%a5%8d%e0%a4%b5-%e0%a4%85%e0%a4%b0%e0%a5%8d%e0%a4%a5%e0%a4%b5%e0%a5%8d%e0%a4%af%e0%a4%b5/?utm_source=rss&utm_medium=rss&utm_campaign=%25e0%25a4%2595%25e0%25a5%258b%25e0%25a4%25b0%25e0%25a5%258b%25e0%25a4%25a8%25e0%25a4%25be-%25e0%25a4%2594%25e0%25a4%25b0-%25e0%25a4%25b5%25e0%25a4%25bf%25e0%25a4%25b6%25e0%25a5%258d%25e0%25a4%25b5-%25e0%25a4%2585%25e0%25a4%25b0%25e0%25a5%258d%25e0%25a4%25a5%25e0%25a4%25b5%25e0%25a5%258d%25e0%25a4%25af%25e0%25a4%25b5 Fri, 05 Jun 2020 14:02:13 +0000 http://shishirkant.com/?p=1812 जब 2020  की शुरआत हुई थी, उस समय अमेरिका की अर्थव्यस्था  अपने निरंतर विस्तार के 126 वे महीने में प्रवेश कर रही थी। ये अमेरिका के इतिहास में आर्थिक प्रगति का सबसे लम्बा दौर था।  उस समय कई  निवेशक और बड़ी कंपनियों के अधिकारी गुपचुप तरीके से ये सवाल उठा रहे थे की, अमेरिका की आर्थिक प्रगति का ये दौर कब तक चलने वाला हिअ ? आखिर वो कौन सी वजह होगी जो हमें अंततः एक बार फिर से आर्थिक सुस्ती के गर्त में धकेल देगी ?

          अब जबकि कोरोना वायरस का प्रकोप पूरी दुनिया में फ़ैल चुका है।  वित्तीय बाज़ारों में क़तल ऐ आम मचा हुआ है।  निवेशकों को हर हफ्ते खरबों डॉलर का नुकसान हो रहा था।  आज  दस वर्ष के अमेरिकी बांड पर रिटर्न एक प्रतिशत से भी काम रह गया है, तो बहुत से लोग खुद को आर्थिक सुस्ती के लिए मानसिक तौर पर तैयार कर रहे हैं।

          कोरोना वायरस का संक्रमण फैलने से पहले , दुनिया के कई बड़े निर्यातक देशों में उत्पादन  सेक्टर का आउटपुट (PMI) 2019 में लगातार गिरयात की ओर बढ़ रहा था।  व्यापारिक संघर्ष के तनावोंki वजह से जो अनिश्चिता उत्पन्न हुई थीम उस कारन से जापान , जर्मनी और नार्थ कोरिया जैसे कई देश में मैन्युफैक्चरिंग सेक्टर का आउटपुट गिर रहा था और मैन्युफैक्चरिंग का वैश्विक PMI 50% से भी नीचे चला गया था . जिसका मतलब था की वर्ष 2019में विश्व की अर्थवयस्था आधिकारिक रूप से सिमट रही थी ।  ‘पुराने औधोगिक’ और सामान के उत्पादन की इस गिरावट के दौरान सेवा  क्षेत्र और उपभोक्ता बाजार के विस्तार के चलते विश्व अर्थवयस्था ली गतिविधियों में प्रगति हो रही थी , फिर दुनिया के विकासशील देश हो या विकसित देश, दोनों में सेवा क्षेत्र और उपभोक्ता बाजार में ही रोज़गार के अधिकतम अवसर उत्पन्न हो रहे थे।  इन्ही कारणों से वित्तीय बाज़ारों में उछाल आ रहा था और निवेश पर अच्छा रिटर्न मिल रहा था।

          लेकिन, आज कोरोना वायरस के संक्रमण ने सीधे उपभोक्ताओं  केंद्रों यानी चीन और एशिया की अन्य प्रमुख अर्थव्यस्थाओं पर प्रहार किया है, इसका नतीजा ये हुआ की विकास के इन दो क्षेत्र में आर्थिक गतिविधियां ठहर गयी है। इस बात की सम्भावना अधिक है की इन देशों में उत्पादकता के पूर्व स्तर तक पहुंचने की प्रक्रिया बेहद तकलीफदेह और धीमी गति वाली होगी और इसी कारण से उपभोक्ताओं की क्रय क्षमता विकसित होने और बाजार की चमक दोबारा वापस आने में भी अधिक समय लगेगा। जहाँ तक सप्लाई चेन की बात है चीन ने केवल इनके क्षेत्रीय व्यापारिक सरप्लस के संग्राहक की भूमिका  (जापान और नार्थ कोरिया जैसे अन्य देशों से इनपुट जुटा कर फिर इन उत्पादों का मूल्य बढ़ाकर इन्हें निर्यात करना ) निभाई है, बल्कि वो इन तैयार उत्पादों के कच्चे माल और प्रबंधन एवम नियमन में भी योगदान दे रहा है , यहाँ तक की व्यापार युद्ध के बावजूद अमेरिका और अन्य देशों की बहुराष्ट्रीय कम्पनियों अपने उत्पादों के कल-पुर्जे के लिए चीन पर निर्भर है।  कोरोना वायरस के प्रभाव से तमाम कच्चे माल की सप्लाई चेन में आ रही समस्या बहुत ही कम्पनियाँ अपने उत्पादों के मूल्य निर्धारण करने की क्षमता खो चुकी हैं, अब उनका निर्धारण ग्राहकों के हाथ में चला गया है।  इसी की वजह से वो टैरिफ बढ़ने से बड़ी लागत के बावजूद अपने उत्पादों का मूल्य बढ़ाने में असमर्थ साबित हो रही हैं।  लेकिन , आज बहुत सी ऐसी कम्पनियों के पास अपने सामान की कीमतें बढ़ाने के सिवा कोई चारा नहीं बचा है, इसलिए ऐसी बहुत सी कंपनियों को ये भय है की उनके ग्राहक हाथ से निकल जाएंगे। 

          ऐसा लग रहा है की वायरस की संक्रमण की आशंका और भय के कारण सेवा क्षेत्र और हॉस्पिटैलिटी सेक्टर  की गतिविधियों में दोबारा सक्रियता लौटने में काफी समय लगने वाला है। अमेरिका भी इसकी भयावता को खूब समझ रहा है, क्युकी वहां S&P कम्पनियों का 43% का राजस्व दूसरे देशों से आता है, इनमे भी एशियाई देश उनके सबसे ज्यादा तेज़ी से विकसित हो रहे बाज़ारों में यूरोपीय देश इससे थोड़ी ही कम विकास दर के साथ दूसरे नंबर पर आते हैं। ऐसे में आज कोई भी देश या कंपनी बाकी दुनिया से अलग दिवप् नहीं रह गए हैं और अमेरिका की बहुत सी कंपनियां अपनी सेवाओं और विस्तार लिए कोरोना वायरस के प्रकोप से प्रभावित क्षेत्रों पर निर्भर है। 

          आज कोरोना वायरस को लेकर जिस तेज़ी से भय फ़ैल रहा है, तो ज़मीनी हक़ीक़तों से   वाबस्ता रहना बेहद महत्पूर्ण है।  और जहाँ तक संभव हो, वहीँ तक भविष्य को लेकर दूरदर्शी रखना ठीक होगा।  हो सकता है की कोरोना के कारण मध्यम और छोटे दौर के लिए बाज़ारों में उठा-पटक देखने को मिलती रहेगी।  लम्बे समय की प्रगति के लिए कौन से विचार अधिक प्रभावी होंगे और पूँजी वितरण के लिए किन सिद्धांतों पर अमल करना अधिक असरदार होगा ? और मंदी के इस दौर में किस तरह से लाभ कमाया जा सकता है ? सेवा क्षेत्र और उपभोक्ता कम्पनियों की बात करें, तो आर्थिक सुस्ती के इस दौर में उनके कौन से उत्पाद और सेवाओं को नए सिरे से ग्राहकों को लुभाने के लिए परिवर्तित किया जा सकता है ? वैकल्पिक पूँजी निवेशकों के लिए स्थानीय पूँजी बाजार को कहाँ स्थानांतरित करने से प्रगति के नए अवसर प्राप्त हो सकते हैं ? आगे ये देखना बहुत महत्वपूर्ण होगा।


          शिशिर कान्त सिंह

          ]]>
          1812