Login Form in Python GUI with MYSQL and MSSQL Connection

In python, if we want to Design Login Form with database authentication with MYSQL or MSSQL then we have to follow the following process with step by step guide. 

Here we will learn How to Design Login Form in Python GUI with MYSQL connection in Python or SQL Server Connection in Python
Design Login Form in Python Tkinter


First we have to Create table For authentication with following field Name:
Login_tbl
usrname passwrd
sko tech

Same type of table we create in MSSQL. 

After that we will use following tkinter widget:
Name Tkinter Wiidget
Bannerlabel  Label
UserLabel  Label
PassLabel  Label
UserTxt  Entry
PassTxt  Entry
LoginBtn  Button

After that we will proceed with following points:

  1. Login Form Design in Python GUI with MYSQL Connection
  2. Login Form Design in Python GUI with MSSQL Connection

Now we will first Start with MYSQL connection then MS SQL Server Connection.

(1). Login Form Design in Python GUI with MYSQL Connection :

Now, first we will import ‘mysql.connector’ for connection. Then write code for establish connection with MYSQl after that write code for query like following way:

import mysql.connector as mysqlconnector
import tkinter as mytk
from tkinter import *
import tkinter.messagebox as mymessagebox

MyLoginForm = mytk.Tk()
MyLoginForm.title('Login Form with MYSQL Connection')
#Set Form Size
MyLoginForm.geometry("380x200")

def ClicktoLogin():
    #MYSQL ConnectionString
    mydb = mysqlconnector.connect(host="xxx.xxx.xxx.xx", user="sko", password="mypassword", database="skotechlearn")
    mycursor = mydb.cursor(dictionary=True)
    mycursor.execute("SELECT * FROM login_tbl where usrname = '"+ UserTxt.get() +"' and passwrd = '"+ PassTxt.get() +"';")
    myresult = mycursor.fetchone()
    if myresult==None:
       mymessagebox.showerror("Error", "Invalid User Name And Password")

    else:
       mymessagebox.showinfo("Success", "Successfully Login")
            
    mydb.close()
    mycursor.close()

# Set Tkinter Widget Size Location and Style
Bannerlabel = Label(MyLoginForm, text = "Login Form......", width=40, bg= 'yellow')
Bannerlabel.place(x=20, y=20)

UserLabel = Label(MyLoginForm, text = "User Name:", width=10)
UserLabel.place(x=20, y=60)

UserTxt = Entry(MyLoginForm,  width=27, relief="flat")
UserTxt.place(x=120, y=60)

#Set Focus on User Entrybox in Tkinter
UserTxt.focus()

PassLabel = Label(MyLoginForm, text = "Password :", width=10)
PassLabel.place(x=20, y=90)

PassTxt = Entry(MyLoginForm,  width=27, relief="flat")
PassTxt.place(x=120, y=90)

#Set Password Char in Entry Widget
PassTxt.config(show="*");

LoginBtn = Button(MyLoginForm, text ="Login", command = ClicktoLogin, relief="groove", fg='blue')
LoginBtn.place(x=280, y=140)

MyLoginForm.configure(background='#54596d')
MyLoginForm.mainloop()

When we execute this code. We will see the output looks like bellow.
 
Login Form MYSQL Connection in Python



As you can see we have changed Form, Label color for better look. After successful Login there will be a message displayed like above figure.
Now, Lets come to another point with MSSQL Connection in Python.

(2). Login Form Design in Python GUI with MSSQL Connection :

For MSSQL Connection first we install pymssql.
pip install pymssql

or
pip3 install pymssql

After that we will import pymssql in python code.
 
For Import and for MSSQL Connection String in Python, we will write following code.
 
MSSQL Server Connection in Python

Connection String Code:

# pymssql.connect(MSSQLServerIP, UserName, Password, Database)
pymssql.connect("xxx.xxx.xxx.xx", "myusername", "myPassword", "MyDatabase")


Let’s see how can we connect MSSQL Server with Python Tkinter Login Form?

import pymssql as MSSQLCnn
import tkinter as mytk
from tkinter import *
import tkinter.messagebox as mymessagebox

MyLoginForm = mytk.Tk()
MyLoginForm.title('Login Form with MSSQL Server Connection')
MyLoginForm.geometry("380x200")

def ClicktoLogin():
    #MSSQL Server ConnectionString
    MSSQLdb = MSSQLCnn.connect("xxx.xxx.xxx.xx", "SQLServerUser", "SQlServerPassword", "SQLServerDatabase")
    mySQLcursor = MSSQLdb.cursor()
    mySQLcursor.execute("SELECT * FROM login_tbl where usrname = '"+ UserTxt.get() +"' and passwrd = '"+ PassTxt.get() +"';")
    mySQLresult = mySQLcursor.fetchone()
    if mySQLresult==None:
       mymessagebox.showerror("Error", "Invalid User Name And Password")

    else:
       mymessagebox.showinfo("Success", "Successfully Login")
            
    MSSQLdb.close()
    mySQLcursor.close()

Bannerlabel = Label(MyLoginForm, text = "MSSQL Server Login Form......", width=40, bg= '#81907E', fg='white')
Bannerlabel.place(x=20, y=20)

UserLabel = Label(MyLoginForm, text = "User Name:", width=10, bg='#FFE6D8')
UserLabel.place(x=20, y=60)

UserTxt = Entry(MyLoginForm,  width=27, relief="flat")
UserTxt.place(x=120, y=60)

#Focus of User Entrybox in Tkinter
UserTxt.focus()

PassLabel = Label(MyLoginForm, text = "Password :", width=10, bg='#FFE6D8')
PassLabel.place(x=20, y=90)

PassTxt = Entry(MyLoginForm,  width=27, relief="flat")
PassTxt.place(x=120, y=90)

#Set Entry box Password Char in Tkinter
PassTxt.config(show="*");

LoginBtn = Button(MyLoginForm, text ="Login", command = ClicktoLogin, relief="groove", fg='blue')
LoginBtn.place(x=280, y=140)

MyLoginForm.configure(background='#FFE6D8')
MyLoginForm.mainloop()


After the execution of this code in python, the following output will present.

Login Form MSSQL Connection in Python


This way you can easily Create or Design Login Form in Python GUI with Tkinter and Connect Login Form with MSSQL in Python Or Connect Login Form with MYSQL in Python.

MySQL Connection in Python with MYSQL Select Query in Python

When we want to connect MYSQL Database with application then we have to first consider about MYSQL Connection Driver and MySQL ConnectionString. So here we will describe MYSQL Database Connection in Python or MYSQL connection in Python with database in three ways. 

  1. Using Pyodbc in MYSQL Connection
  2. Using mysql.connector for MYSQL Connection
  3. Using pymysql for MYSQL Connection

Fist thing we have to know that if we want to connect any type of Database organization, then we have to use Driver from particular database organization like MYSQL. So, Lets Start from pyodbc in python.


(1). Using Pyodbc in MYSQL Connection :

For using pyodbc, you have to install pyodbc through pip. Now, lets know the following connection string of pyodbc.


pyodbc.connect("DRIVER={Driver_Name}; User=Server_User; Password=server_Password; Server=localhost/server IP; Database=DatabaseName;")

So, Write following code to show database table’s record in following way:
import pyodbc 

mysqlcn = pyodbc.connect("DRIVER={MySQL ODBC 8.0 ANSI Driver}; User=sko; Password=xxxxxx; Server=xxx.xxx.xxx.xx; Database=mydatabase; ")
dbcursor = mysqlcn.cursor() 
dbcursor.execute("SELECT * FROM TestTable") 
myfield = dbcursor.fetchone() 
# Loop to fetch one by one data.
while myfield:
      # Print partuculat column data from table
print (myfield[0]) 
myfield = dbcursor.fetchone()

#Now Close cursor and connection
dbcursor.close()
mysqlcn.close() 

In this code we use “MySQL ODBC 8.0 ANSI Driver” in pyodbc. 

This will show following output:

MySQL Connect using Pyodbc Output

Show MySQL Data in Listbox in Python


If you want to show data or you can use MYSQL Select Query in Python to show data in Listbox then following code will be help in you coding.

Show Database Record in Listbox:

import tkinter as mytk
from tkinter import *
import pyodbc 

MytkForm = mytk.Tk()
MytkForm.title('MySQL with pyodbc') MytkForm.geometry("250x100") # Create Listbox MyTklist = mytk.Listbox(MytkForm)
#Clear Listbox MyTklist.delete(0,END) mysqlcn = pyodbc.connect("DRIVER={MySQL ODBC 8.0 ANSI Driver}; User=sko; Password=xxxxxx; Server=xxx.xxx.xxx.xx; Database=mydatabase;") dbcursor = mysqlcn.cursor() #MySQL Select Query in Python dbcursor.execute("SELECT * FROM TestTable") myfield = dbcursor.fetchone() while myfield: # Add Field data in Listbox MyTklist.insert(END,myfield[0]) myfield = dbcursor.fetchone() dbcursor.close() mysqlcn.close() MyTklist.pack() MytkForm.mainloop()

OUTPUT: 

MySQL Data Show in Listbox in Python



(2). Using mysql.connector for MYSQL Connection

In this point we will learn how to use mysql.connector for database connection and also learn how to List MYSQL data through column name in python. 

Mysql.connector ConnectionString in Python


mysql.connector.connect(host="XXX.XXX.XXX.XX", user="Database_User", password="Database_Password", database="DatabaseName")

Now Lets, see how to show data?
import mysql.connector
#ConnectionString
mydb = mysql.connector.connect(host="XXX.XXX.XXX.XX", user="sko", password="mypassword", database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM TestTable")
myresult = mycursor.fetchall()
for mycol in myresult:
   # Get Second Column's row List
   print(mycol[1])

mydb.close()
mycursor.close() 

OUTPUT:

MySQL Connect using mysql.connector


In this given output, you can see, we show only second column data through “mycol[1]” this code. 

MySQL Column Value show through Column Name in Python in Listbox: 


As you saw before, we are showing data through Column Number, but if we have more columns and want to show particular column value then we have to determine Column Name

So, through following way you can use to show column value through Column Name. You have to add following code in cursor method.


mycursor = mydb.cursor(dictionary=True)

Lets see with full details:
import mysql.connector
import tkinter as mytk
from tkinter import *

MytkForm2 = mytk.Tk()
MytkForm2.title('MySQL with mysql.connector') MytkForm2.geometry("270x120") MyListData= mytk.Listbox(MytkForm2)
mydb = mysql.connector.connect(host="XXX.XXX.XXX.XX", user="sko", password="mypassword", database="mydatabase") #Fetch Particular Column Value through Column name with using dictionary mycursor = mydb.cursor(dictionary=True) mycursor.execute("SELECT * FROM TestTable") myresult = mycursor.fetchall() for MyColName in myresult: MyListData.insert(END, MyColName ["MyDetails"]) mydb.close() mycursor.close() MyListData.pack() MytkForm2.mainloop()

Now, This will Show output according to Column Name.
MySQL Data in ListBox using column name in python


(3). Using Pymysql for MYSQL Connection

You can use another connector in python that's call pymysql. First you have to install pymysql. After that you have to use following connection string.
pymysql.connect(host="XXX.XXX.XXX.XX", user="MySQLUsername", password="MYSQLPassword", database="MYSQLDatabase")

Then write following code to show data in Python.
import pymysql

# database connectionstring
connmysql = pymysql.connect(host="XXX.XXX.XXX.XX", user="sko", password="mypassword", database="mydatabase")
cursordb = connmysql.cursor()

# execute your query through execute().
cursordb.execute("SELECT * FROM TestTable")

# get all row through fetchall().
data = cursordb.fetchall()
for colnm in data:
    print(colnm[0])

# close connection
connmysql.close()

OUTPUT:



Conclusion: You can use any one of these method. You will find some performance differences. But you will find exact result using any connector in python.

So, this way you can Connect MYSQL in Python with step by step process.

How to Make Image Selected Area Transparent in Gimp

In this post SKOTechLearn will describe How to Make Image Selected Area Transparent in GIMP or Image Selected Area Transparent in GIMP. As you know GIMP provide image processing of all kind of image formats. You can modify, beautify and change format of image through this application.

Selected Area Transparent in Gimp

Here, we will describe three way to make area transparent in GIMP. You just follow the steps described bellow with following points:

 

  1. Use ‘Rectangle Select Tool’ To Make Selected Area Transparent
  2. Use ‘Free Select Tool’To Make Selected Area Transparent
  3. Use ‘Eraser Tool’To Make Selected Area Transparent

So, First Open your Image in Gimp. Then proceed with following way:

(1). Use ‘Rectangle Select Tool’ To Make Selected Area Transparent :

If you want to use ‘Rectangle Select Tool’, you have to follow the steps in GIMP.

 1.
 Right click on Image in Gimp.

 2.
 A drop down menu will appear, Go to ‘Layer’ option.

 3.
 In ‘Layer’, go to ‘Transparency’ option.

 4.
 Then Select ‘Add Alpha Channel’.

Let's see the instruction given in following figure.

 
Add Alpha Chanel In Gimp


 5.
 After that select ‘Rectangle Select Tool’ from ‘Tools’.

 6.
 Now, select area where you want to make selection transparent.

 7.
 And Press ‘Delete’ from Keyboard.

Select Tool For Selection Transparent in Gimp



Now, let's proceed to second process.

 

(2). Use ‘Free Select Tool’ To Make Selected Area Transparent :

Like above given Points for ‘Add Alpha Channel’. You have to do same in this process. 

 (Right Click) Image >> “Layer” >> “Transparency” >> “Add Alpha Channel” 

 1.
 After this Process, you have to go to ‘Tools’ window and select ‘Free Select Tool’.

 2.
 Then point on area which you want to make transparent.

 3.
 And then join start and end point of ‘Free Select Tool’ then Press ‘Delete’ Button from Keyboard.




This will make desire area transparent.

 

(3). Use ‘Eraser Tool’ To Make Selected Area Transparent :

Same way you have to select ‘Add Alpha Channel’ like first process.

(Right Click) Image >> “Layer” >> “Transparency” >> “Add Alpha Channel” 

 1.
 After that Select ‘Eraser Tool’.

 2.
 Then go to ‘Eraser ToolProperties and Increase or decrease EraserSize’ according to area selection.

 3.
 Then click on area of Image.

This will make eraser area transparent.
Eraser Tool For Selection Transparent in Gimp


Note: If you want to increase or decrease transparency level, you have to simply go to ‘Eraser’ tool’s Properties window and Increase or decrease ‘Opacity’ from 0 to 100%.

This is the simplest and easy way to manually select area and make it transparent. 

In Gimp, you will find many other tools that provide facility to transparent selected part in GIMP. So, this way you can make Image Selected Area transparent in GIMP with SKOTechLearn easy tips.

Add Itmes in ComboBox in Tkinter Python with Loop Example

Here, we will discuss and Learn about Tkinter Combobox in Python. Here we will learn how to Add Items in Combobox in Tkinter or Add Items in ComboBox in Tkinter through Loop in Python. So, we will proceed with step by step Process with following points.


  1. Manually Add Items in ComboBox Tkinter in python
  2. Add Items in ComboBox Tkinter in python through Loop

Now, lets Learn point wise given bellow.

 How To Get value From Textbox to Label in Tkinter in Python?

(1). Manually Add Items in ComboBox Tkinter in python :

If you want to add items in design time or manually then you have to write following code in Python. Tkinter provide ttk class to show combobox and its attributes. So, Manually add items process code in tkinter described in following way:
import tkinter as tk
from tkinter import *
from tkinter import ttk

MyrootDialog = tk.Tk(className="Add Items in Tkinter Combobox")
#Set Tkinter window Size
MyrootDialog.geometry("300x100")

mytkcombo = ttk.Combobox(MyrootDialog, values=['SKO', 'Tech', 'Learn'])
#Set Combobox Position in Python
mytkcombo.place(relx=0.5, rely=0.3, anchor='center')
mytkcombo['state'] = 'readonly'
#mycombo.pack()

MyrootDialog.mainloop()
When you run this code, this will show you following output.

Manually Show items in Combobox Tkinter
Items in Tkinter ComboBox in Python


So, In this way you can add items in ComboBox tkinter in Python through static way. Now let’s Learn about dynamic way at run time.


(2). Add Items in ComboBox Tkinter in python through Loop :

Now, if You want to add itmes in tkinter combobox at runtime with loop or loop to add items in tkinter combobox in python, you have to implement some code in python like bellow: 

Example 1:
import tkinter as tk
from tkinter import *
from tkinter import ttk

MyrootDialog = tk.Tk(className="Add Items in Tkinter Combobox")
#Set Tkinter window Size
MyrootDialog.geometry("300x100")

mytkcombo = ttk.Combobox(MyrootDialog)
# For Loop
for x in range(5):
   # Add itmes in combobox through Loop code
   mytkcombo['values']= tuple(list(mytkcombo['values']) + [str(x)])
mytkcombo.place(relx=0.5, rely=0.3, anchor='center')

MyrootDialog.mainloop()

This is the dynamic way to show items in combobox at run time through loop. This will show following output:
Loop Items in ComboBox Tkinter
Loop Items in ComboBox



Show Month in Combobox Tkinter through Loop

Example 2:

Now, lets See another Example to showing month name in ComboBox through Loop . In this example we use array list to add items in ComboBox Python.
import tkinter as tk
from tkinter import *
from tkinter import ttk
import calendar

MyrootDialog = tk.Tk(className="Add Items in Tkinter Combobox")
#Set Tkinter window Size
MyrootDialog.geometry("300x100")

mytkcombo = ttk.Combobox(MyrootDialog)
# Define Array List
strList=['']
for mnt in range(1, 13):
   #Add Month Name through Loop
   strList.append(calendar.month_name[mnt])
#Add Items in Tkinter Combobox through Array
mytkcombo['values'] = strList
mytkcombo.place(relx=0.5, rely=0.3, anchor='center')

MyrootDialog.mainloop()




After running this code you will see the output like following way:

Show Month In ComboBox in Tkinter
Show Month Name in Tkinter ComboBox in Python


So, these are the three way to show or Add Items in Combobox in tkinter in Python, you can choose anyone according to your application or software requirement.

Steps to Change Dark Theme to Light Theme in Visual Studio Code

If you like Light Theme in Code Editor in Visual Studio Code then here SKOTechLearn will describe the steps to Change Dark Theme to Light Them in Visual Studio Code. And Here we will also describe the steps to Customize Color or Theme in Visual Studio Code.

Dark theme to Light Theme in Visual Studio Code

By default VS Code contain Dark theme. You know that Visual Studio is highly customized code editor compare to all other code editor. And you can find many feature to change Look and Feel in Visual Studio Code.

Change visual studio code background color

Now, we can choose any one process for Change Code Editor Color in Visual Studio Code:

  1. Change Theme of Visual Studio Code through Shortcut Key
  2. Change Theme of Visual Studio Code through Settings
  3. Change Color Theme of Visual Studio Code through Code


(1). Change Theme of Visual Studio Code through Shortcut Key:

When you open VSCode, and want to change theme, then simply you have to press two different shortcut Key one by one same time.

Press First Shortcut Key:  CTRL + K 
After that Press second Shortcut Key:  CTRL + T 

Now, you will see a drop down Option Box “Select Color Theme (Up/Down Keys To Preview)” will appear containing list of existing theme like bellow:

Change Theme in Visual Studio Code through Shortcut Key

This Option Box contain two types of Theme Category first is “light themes” and second is “dark themes”. If you want to change VSCode in light theme, then choose first category.


(2). Change Color Theme of Visual Studio Code through Settings:

If you want to proceed for color change through VSCode settings, then you have to follow the steps:

1.
First Go to “File” menu.

2.
Find “Preferences” and select it.

3.
And then select “Color Theme[Ctrl+K Ctrl+T]” option from it.

4.
Now, a drop down list will appear containing themes options. Choose anyone which you like.

Settings to change Theme color in Visual Studio

As you can see, in this way you can change Dark Theme to Light Theme in VSCode.

(3). Change Color Theme of Visual Studio Code through Code:

This is very interesting process to Change Look and Feel Of Visual Studio Code. In this Process you can change every Part of VSCode Tool's color according to your desire. You have to Simply proceed with following way:

1.
Same as above given steps, you have to first go to “File” menu then “Preferences” then “Settings”.

2.
You will find “Settings” Tab will appear. Go to Search Bar and search for “.json”.

3.
You will get “Edit in Settings.json” option. Just click on it.

4.
Now “Settings.json” file will display. Add color code like bellow:

{
     "workbench.colorCustomizations": {
     //For Code editor Color Change
     "editor.background": "#edeafa",
     "editor.foreground": "#4b4548",

     //For Sidebar Color Change
     "sideBar.background": "#fddcaa",
     "sideBar.foreground": "#612144", 

     //Change Activity Bar Color
     "activityBar.background": "#7f61a7",
     "activityBar.foreground": "#c5ff3e",
     "activityBar.inactiveForeground": "#6dc58f"
     }
} 

After writing this code, save it and see what happen:
Customise Theme Color in Visual Studio Code

As you can see you can manually create theme in VSCode.

So, this way you can easily Customize Theme Color of Visual Studio Code. And also set Light theme in VSCode.

Steps to Get Entry Or Text Value in Label in Python Tkinter

In python using Tkinter, there are two types of Input Box first is Tkinter Entry Box and Second is Tkinter Text. And if you want to get String or Get Value from Entry in Tkinter or Get Tkinter Text Value in Python then here you will find detailed process to consider how to use it in your Project.


How to use Tkinter Label in Python with features


Important Note: We Find that Text widget can not work in Tab Order. You have to write more code effort to perform Tab order in Text in Tkinter. But if you use Entry widget in python. There will no problem in tab order.

Now Let’s Learn How to Get Value from Entry in Python Tkinter or Get Value from Text with following way:

  1. Get Entry Value in Label in Python Tkinter
  2. Get Text Value in Label in Python Tkinter

So, Let’s Start.

(1). Get Entry Value in Label in Python Tkinter :

As you know that for perform any action in Python you have to define Function. So for getting value you have to define function as bellow and Get Entry Value.

Python Code:
from tkinter import *

MyRootDialog=Tk()
#Set Tkinter Size And Location
MyRootDialog.geometry("200x150+100+100")

#Set Tkinter Title
MyRootDialog.title("Get Input Value in Label")

# Define Function for get Value
def Get_MyInputValue():
     getresult = MyEntryBox.get()
     myTKlabel['text'] = getresult

# Create Tkinter Entry Widget
MyEntryBox = Entry(MyRootDialog, width=20)
MyEntryBox.place(x=5, y=6)

myTKlabel = Label(MyRootDialog, borderwidth=1, relief="ridge", height=3, width=25)
myTKlabel.place(x=4, y=42)

#command will call the defined function
MyTkButton = Button(MyRootDialog, height=1, width=10, text="Get text", command= Get_MyInputValue)
MyTkButton.place(x=4, y=112)

mainloop()

One more thing here you can use get value in Label through following two way:

myTKlabel['text'] = getresult

or

myTKlabel.config(text = getresult)

You can use it according to your desire. Both will present same result.

Output:
Get Entry value in Tkinter in Python

You can also Set Tkinter window in Center Location.

(2). Get Text Value in Label in Python Tkinter :

Now if you use Tkinter Text widget in python then you have to write following code to get Tkinter text in python.

Note: Get Value from Tkinter Entry Widget code: MyEntryBox.get()
And for get Value from Tkinter Text Widget code: MyTktextBox.get("1.0", 'end-1c')

In Text Widget you have to pass Index inside Get() function:

Code:
from tkinter import *

MyRootDialog=Tk()
#Set Tkinter Size And Location
MyRootDialog.geometry("200x150+100+100")

#Set Tkinter Title
MyRootDialog.title("Get Input Value in Label")

# Define Function for get Text Value
def Get_TKTextValue():
      myTxtresult = MyTktextBox.get("1.0", 'end-1c')
      myTKlabel.config(text = myTxtresult)

# Create Tkinter Text Widget
MyTktextBox=Text(MyRootDialog, height=1, width=20)
MyTktextBox.place(x=5, y=6)


myTKlabel = Label(MyRootDialog, borderwidth=1, relief="ridge", height=2, width=25)
myTKlabel.place(x=4, y=42)

#command will call the defined function
MyButton = Button(MyRootDialog, height=1, width=10, text="Get text", command= Get_TKTextValue)
MyButton.place(x=4, y=92)

mainloop()

Now, when you run you code, this will present following output.


Different types of Multi Line String process in Python


Output:
Get Text Value in Python

So, these above given code process is use to Get Tkinter Text Value in Label or Get Entry Value in Python.

String in Python with Single, Multi-Line, Concatenate in Python

First of all you have to understand about String in Python. Basically a String is a collection of characters which is used to define a word or sentence or paragraph with single or multiple lines. And here we also describe some basic Format of String or Integer Concatenation in Python.

Use String in Python

In Python, when we define a string, it will be define either Single (‘ ’) Quote or Double Quote ( “ ”).
For simple example you can use print() function for display simple word or sentence as form of string as given bellow:

print( "SKOTechLearn" )
print( 'SKOTechLearn' )
Output:
>>>
SKOTechLearn
SKOTechLearn
>>>


So, let’s see the types and use of String with following way:

  1. Single Line String using Variable 
  2. Use String to Passing value in Function 
  3. Multi-Line Sting using Variable 
  4. Concatenate Strings in Python 
  5. Concatenate integer or number with String


(1). Single Line String in Python using Variable :

Suppose you want to store your word or sentence and show during process then we simply assign a Variable.

mystrng = "Hello SKOTechLearn"
print(mystrng)
Output:
>>>
Hello SKOTechLearn
>>>


(2). Use String to Passing value in Function in Python:

This is very important point which is used in every programming process. Here you can use string for passing in other function or references.

You can simply cover following points:

➤ Python pass function as argument with parameters
➤ How to pass string as parameter in python function?
➤ Python pass function name as argument
➤ Python call function from string with arguments

You have to simply learn following process:

Myfstr = "skotechlearn"
MyPFunc( Myfstr )

def MyPFunc ( Myfstr ):
    # upper() method is use to show Characters in Capital Letters
    skstr = Myfstr.upper()
    print (skstr)
Output:
>>>
SKOTECHLEARN
>>>

You can simply use this process with many ways according to your application requirement process.


(3). Multi-Line Sting in Python using Variable :

As you can understand how to store or show string in python, but when you want to store multiline sentence or paragraph on your application, what is the code process we apply?

You have to simply write word or sentence in start and end with Triple Quotes (""" """) or You can simply use “\n” between you sentence with following way:

Multi-line String using Triple Quotes (""" """) :

MyMultilineStr = """This is Triple Quote multiline Sentence
Using Python Code
With Simple output"""
print (MyMultilineStr)
Output:
>>>
This is Triple Quote multiline Sentence
Using Python Code
With Simple output
>>>


Multi-line using “\n” :

MyNextLineStr = "This is multiline Sentence \n Python Code \n With Next Line Process "
print (MyNextLineStr)
Output:
>>>
This is multiline Sentence
Python Code
With Next Line Process
>>>


(4). Concatenate Strings in Python :

There are 4 ways for concatenating string in Python.

First Process:


You can simply use “+” Sign for concatenate word or sentence.

FstStr = "SKO"
SecStr = "Tech"
ThirdStr = "Learn"

FinalStr = FstStr  + " " + SecStr + " " + ThirdStr
print (FinalStr)
Output:
>>>
SKO Tech Learn
>>>


Second Process:


You can simply use “{}{}{}”.format(StrVar1, StrVar2, StrVar3) function.

Tips1: "{}{}{}".format(StrVar1, StrVar2, StrVar3): if you don’t need space between string.
Tips2: "{} {} {}".format(StrVar1, StrVar2, StrVar3) : if you need to add space between string.

Note: Input Number of “{}” Curly Brace according to the number of string variable.

PStr1= "SKO"
PStr2 = "Tech"
PStr3 = "Learn"
PStr4 = "Tips"

#concatenate String without space
print("{}{}{}{}".format(PStr1, PStr2, PStr3, PStr4)) 

# concatenate String with space
print("{} {} {} {}".format(PStr1, PStr2, PStr3, PStr4))
Output:
>>>
SKOTechLearnTips
SKO Tech Learn Tips
>>>


Third Process:


In this process you can use "% s % s % s" % (StrVr1, StrVr2, StrVr3). Here you can add number of “% s” according to number of string value or variable.

"% s % s % s" : if you want to add space during concatenating variable. This will show sentence with space.
"% s% s% s" : This will show Concatenate variable without space.

For Example:
myVr1 = "This"
myVr2 = "is"
myVr3 = "Concatenate"
myVr4 = "Code"
#Sentance without space
print("%s%s%s%s" % (myVr1, myVr2, myVr3, myVr4)) 

# Add space between word or sentence
print("%s %s %s %s" % (myVr1, myVr2, myVr3, myVr4))
Output:
>>>
ThisisConcatenateCode
This is Concatenate Code
>>>


Forth Process:


Use .join for concatenate in python. For Simply you have to follow following syntax:

Concatenate Without Space: "".join([SkVr1, SkVr2, SkVr3])
Concatenate With Space: "".join([SkVr1, SkVr2, SkVr3])

For Example:
SkVr1 = "Learn"
SkVr2 = "Concatenate"
SkVr3 = "process"
# Concatenate process without space
print("".join([SkVr1, SkVr2, SkVr3])) 
# Concatenate process with space 
print(" ".join([SkVr1, SkVr2, SkVr3]))
Output:
>>>
LearnConcatenateprocess
Learn Concatenate process
>>>


(5). Concatenate integer or number in Python with String:

When you will try to concatenate integer in Python with alphabet or sentence, you will get the following error with normal process like bellow:
print(1 + "This is Alphabet")
>>>
Traceback (most recent call last):
 print(1+"This is Alphabet")
TypeError: unsupported operand type(s) for +: 'int' and 'str
>>> 

As you can see the above error will display. So, we try following way to solve this problem. There are four process for Concatenating Integer with String:

Process 1:
 Simply input number inside Double Quote(“ ”):

print("2"+ ". This is Alphabet")
Output:
>>>
2. This is Alphabet
>>>


Process 2:
 Using str() for converting Integer :

mynum = 2
combstr = "This is Alphabet"
print(str(mynum) + "=  " + combstr)
Output:
>>>
2= This is Alphabet
>>>


Process 3:
 Using .format method for concatenate of integer :

mynum = 2
combstr = "This is Alphabet"
print "Point No. {} is - {} for concatenate with Integer".format(mynum, combstr)
Output:
>>>
Point No. 2 is - This is Alphabet for concatenate with Integer
>>>


Process 4:
 Using “% s” for Concatenate integer :

mynum = 2
combstr = "This is Alphabet"
print("No. % s % s" % (mynum, combstr))
Output:
>>>
No. 2 This is Alphabet
>>>


So Friends, these are the process for Using String in Python, easily show Multi-line String in python, Passing String in function in Python, Concatenate String in Python, Concatenate Integer in Python.