Python Devlopment






Strings



2.2 Python Strings:

In python, string can be represented using either single quote or double quote like “Hello” is same as “‘Hello’ and strings can be printed using print statement.

Example 1:

>>>print(“Hello World!”)
Hello World!
>>>print(‘Hello World!’)
Hello World!

Example 2:

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Output: 
e

Example 3:

Substring. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Example 4:

The len() method returns the length of a string:

a = "Hello, World!"
print(len(a))

Output:
13

Example 5:

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Output: 
hello, world!

Example 6:

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

Output: 
HELLO, WORLD!

Example 7:

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Output: 
Jello, World!
Exercise:

Write a function that accepts a text and a character as argument and returns the no. of occurrences of the character in the text.

def count(text, ch):  #Definition
    n = 0 
    for i in text: 
        if ch == i: 
            n += 1 
    return n 

#calling statement
n=count(text,ch)      #Return type function