Search This Blog

Wednesday, 15 December 2021

Strings in Python

 

Python Strings

html5 templates

Python string is a built-in type text sequence. It is used to handle textual data in python. Python Strings are immutable sequences of Unicode points. Creating Strings are simplest and easy to use in Python.

We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same.

Example : 

a = "Hello"
b= 'Java'
print(a+" "+b)

output of above example  :

Hello Java

Accessing Python Strings

  • In Python, Strings are stored as individual characters in a contiguous memory location
  • The benefit of using String is that it can be accessed from both the directions (forward and backward).
  • Both forward as well as backward indexing are provided using Strings in Python.
  • Forward indexing starts with 0,1,2,3,.... 
  • Backward indexing starts with -1,-2,-3,-4,....
str[0]='P'=str[-6] ,
str[1]='Y' = str[-5] ,
str[2] = 'T' = str[-4] ,
str[3] = 'H' = str[-3] ,
str[4] = 'O' = str[-2] ,
str[5] = 'N' = str[-1].

Python String Example

Here, we are creating a simple program to retrieve String in reverse as well as normal form.

name="NOTES"
length=len(name)
i=0

for n in range(-1,(-length-1),-1):
    print(name[i],"\t",name[n])
    i+=1

output : 

N         S

O         E

T         T

E         O

S         N

Python Strings Operators

To perform operation on string, Python provides basically 3 types of Operators that are given below.

  • Basic Operators.
  • Membership Operators.
  • Relational Operators.

1. Basic Operators

There are two types of basic operators in String + and *.

String Concatenation Operator (+)

str1="Java"
str2="Notes"
print(str1+str2)

Output :

JavaNotes

String Concatenation Operator (+)

ExpressionOutput
"20"+"40""2040"
"java"+"123""java123"
"java01"+"notes01""java01notes01"

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

for example :
print("java"+01)

output :

Traceback (most recent call last):
  File "main.py", line 1, in
    print("java"+01)
    TypeError: Can't convert 'int' object to str implicitly

Python String Replication Operator (*)

Replication operator uses two parameters for operation, One is the integer value and the other one is the String argument.


The Replication operator is used to repeat a string number of times. The string will be repeated the number of times which is given by the integer value.


For Example :

print("java" * 5)
print(3 * "Python")

output : 

javajavajavajavajava
PythonPythonPython

Python String Replication Operator (*)

ExpressionOutput
"ArcX" * 2"ArcXArcX"
3 * '5''555'
'@' * 5'@@@@@'

NOTE: We can use Replication operator in any way i.e., int * string or string * int. Both the parameters passed cannot be of same type.

2 . Python String Membership Operators

Membership Operators are already discussed in the Operators section. Let see with context of String.


There are two types of Membership operators :

  1. in - "in" operator returns true if a character or the entire substring is present in the specified string, otherwise false.
  2. not in - "not in" operator returns true if a character or entire substring does not exist in the specified string, otherwise false.

lets see the example :

str1="JavaNotes"
str2="Java"
str3="Notes"
str4="Users"

print('Exmple of in operator ::')
print(str2 in str1)
print(str3 in str1)
print(str4 in str1)
print()
print(str2 not in str1)
print(str3 not in str1)
print(str4 not in str1)

output :

Exmple of in operator ::

True
True
False


False
False
True

3. Python Relational Operators 

All the comparison (relational) operators i.e., (<,><=,>=,==,!=,<>) are also applicable for strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order).


Example : 

print("Java"=="Java")
print("java">="Java")
print("A"<"a")

output :

True
True
True

Explanation:

The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65, B is 66, C is 67 and so on. The comparison between strings are done on the basis on ASCII value.

Python String Slice Notation

Python String slice can be defined as a substring which is the part of the string. Therefore further substring can be obtained from a string.


There can be many forms to slice a string, as string can be accessed or indexed from both the direction and hence string can also be sliced from both the directions.

Syntax of Slice Operator :

str[start : stop : step ]


other syntax of slice 

str[start : stop]  #items start through stop-1

str[start : ] #items start through the rest of the array

str[ : stop]  #items from the beginning through stop-1

str[ : ]  # a copy of the whole array

example :

s="Monty Python"

print(s[6:10])
print(s[-12:-7])
print(s[-1: :-1]) #reversed all string
print(s[2: 10: 2]) #step = 2
print(s[ : : -1]) #reversed all string
print(s[ : 5]) #from 0 to 4
print(s[3 : ]) #from 3 to end of the string
print(s[ : ]) #copy all strin

output :

Pyth
Monty
nohtyP ytnoM
nyPt
nohtyP ytnoM
Monty
ty Python
Monty Python

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

Continue statement in Python

 

Python Continue Statement

html site templates

Python Continue Statement is a jump statement which is used to skip execution of current iteration. After skipping, loop continue with next iteration. We can use continue statement with for as well as while loop in Python

Continue Statement :

Python Continue Statement Example :

a=0

while a<=5:
    a=a+1
    if a%2==0:
        continue
    print a
print "End of Loop"

output of above example  :

1
3
5
End of Loop

You can use the continue statement to avoid deeply nested conditional code, or to optimize a loop by eliminating frequently occurring cases that you would like to reject.

The continue statement causes a program to skip certain factors that come up within a loop, but then continue through the rest of the loop.

Pass statement in Python

 

Python Pass Statement

create your own web page

In Python, pass keyword is used to execute nothing; it means, when we don't want to execute code, the pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by without executing any code. If we want to bypass any code pass statement can be used.

Python pass Example :

number = 0

for number in range(10):
   number = number + 1
   if number == 5:
      pass   # pass here
   print('Number is ' + str(number))
print('Out of loop')

output of above example  :

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Out of loop

By using the pass statement in this program, we notice that the program runs exactly as it would if there were no conditional statement in the program. The pass statement tells the program to disregard that condition and continue to run the program as usual.

Loops Break in Python

 

Python Break Statement

create a site for free

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You’ll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

Flowchart of break statement :

Let’s look at an example that uses the break statement in a for loop:

number = 0
for number in range(10):
   number = number + 1
   if number == 5:
      break # break here
   print('Number is ' + str(number))
print('Out of loop')

Explanation:

1

In this small program, the variable number is initialized at 0. Then a for statement constructs the loop as long as the variable number is less than 10.

2

Within the for loop, the number increases incrementally by 1 with each pass because of the line number = number + 1.

3

Then, there is an if statement that presents the condition that if the variable number is equivalent to the integer 5, then the loop will break.

4

Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement.

5

To see when we are out of the loop, we have included a final print() statement outside of the for loop.

output of above example  :

Number is 1

Number is 2

Number is 3

Number is 4

Out of loop

This shows that once the integer number is evaluated as equivalent to 5, the loop breaks, as the program is told to do so with the break statement.

The break statement causes a program to break out of a loop.

For Loop in Python

 

Python For Loop

build a site

Python for loop is used to iterate the elements of a collection in the order that they appear. This collection can be a sequence(list or string).

Python For Loop Syntax :

for [variable] in [sequence]:
1

Firstly, the first value will be assigned in the variable.

2

Secondly all the statements in the body of the loop are executed with the same value.

3

Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated.

4

Finally, it continues till all the values in the sequence are assigned in the variable and processed.

Python For Loop Simple Example :

num=2

for a in range (1,6):
    print num * a

output of above example  :

2
4
6
8
10

Python Example to Find Sum of 10 Numbers :

sum=0
for n in range(1,11):
    sum+=n
print sum

output of above example  :

55

Python Nested For Loops

Example of Nested for loop :

for i in range(1,6):
    for j in range (1,i+1):
        print i,
    print

output of above example  :

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

For each value of Outer loop the whole inner loop is executed.

For each value of inner loop the Body is executed each time. 


lets see one more example of patter program :

for i in range (1,6):
    for j in range (5,i-1,-1):
       print "*",
    print

output of above example  :

* * * * *
* * * *
* * *
* *
*

how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...