Python Programming
Topics:

String

It is a case sensitive, non-mutable sequence of characters marked under quotation. It can contain alphabets, digits, white spaces and special characters.

Defining a String


String objects can be defined with one or three pairs of quotes.

Example:
'string'
"string"
'''string'''
"""string"""

In some other languages we use single quotes for single character like 'A' and double quotes for more than one characters like "Apple" but Python has no character types, it treats a character as string of length one. This is why we can use single or double quotes interchagibally for any string definition.

Three pair of quotes are used when you have to define a multiline string or single quotes are part of string. A backslash '\' can also be used to treat quotes as characters under string.

Example:
x = "I don't want to go out in rain"
x = 'I don\'t want to go out in rain'
x = """I said, "I don't want to go out in rain". Understood."""
x = "I said, \"I don\'t want to go out in rain\". Understood."

The value from input() function in Python3 and raw_input() function in Python2 is always a string. Similarly most files and databases also define data as string object. This increases the likelihood of finding a string.

Properties of a string


1. Case sensitive

"hello" == "Hello"
 False

2. Sequence type

     01234
x = "hello"
It is because of the sequential nature of teh string that indexing and slicing is possible. Given any positive or negative index of a string and it will give you the character at that location. Slicing a string from one index to another gives a substring. Syntax: string_object[start_index=0,end_index=len(str)]
x[0]
'h'
x[:2]
'he'
Reverse a string
x[::-1]
'olleh'

3. Non-mutable

Original string object does not change, it rather creates a shallow(separate) copy.

x = "hello"
x.upper()
'HELLO'
print(x)
'hello'
y = x.upper()
print(y)
'HELLO'

4. Concatenation

String can be joined with another string using '+' operator.

"a" + "bcd"
'abcd'

5. Repetition

String objects can repeat its value when multiplied with an integer.

x = "abc" * 3
print(x)
'abcabcabc'

Built-in string functions dir(str)

In [7]:
# Functions working on case of string
x = "indIA Is GReat"
In [6]:
x.lower()
Out[6]:
'india is great'
In [2]:
x.upper()
Out[2]:
'INDIA IS GREAT'
In [3]:
x.capitalize()
Out[3]:
'India is great'
In [4]:
x.swapcase()
Out[4]:
'INDia iS grEAT'
In [5]:
x.casefold()
Out[5]:
'india is great'
In [8]:
x = 'India is great'
In [9]:
x.count('a')
Out[9]:
2
In [10]:
x.index('is')
Out[10]:
6
In [14]:
x.find('is')
Out[14]:
6
In [13]:
x.find('AA')
Out[13]:
-1
In [15]:
x.replace('a','T')
Out[15]:
'IndiT is greTt'

Boolean string functions

startswith() endswith() isalpha() isdigit() isalnum() isprintable() isidentifier()

Objective Questions - String

1. What is the output when following statement is executed?

"a"+"bc"
a) a
b) bc
c) bca
d) abc

2. What is the output when following statement is executed ?

"abcd"[2:]
a) a
b) ab
c) cd
d) dc

3. What is the output when following code is executed ?

str1 = 'hello'
str2 = ','
str3 = 'world'
str1[-1:]
a) olleh
b) hello
c) h
d) o

4. What arithmetic operators cannot be used with strings ?

a) +
b) *
c) –
d) **

5. What is the output when following code is executed?

str1="helloworld"
str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld

6. What is the output of the following code ?

example = ("snow world")
print("%s" %example[4:7])
a) wo
b) world
c) sn
d) rl

7. What is the output of the following code?

example = "snow world"
example[3] = 's'
print example
a) snow
b) snow world
c) Error
d) snos world

8. What is the output of the following code ?

max("what are you")
a) Error
b) u
c) t
d) y

9. Given a string example=”hello” what is the output of

example.count(l)
a) 2
b) 1
c) None
d) 0

10. What is the output of the following code ?

>>>example = "helle"
>>>example.find("e")
a)Error
b)-1
c)1
d)0
In [1]:
# 1. WAP to find is a given string starts with a vowel.
'''
>>> startsWithVowel("Apple")
True
>>> startsWithVowel("banana")
False
'''

def startsWithVowel(str1):
	if str1[0] in "aeiouAEIOU":
		return True
	return False
In [2]:
# 2. WAP to get commonLetters from two string with case and duplicates ignored and the result sorted alpabetically
'''
>>>commonLetters("Google","Apple")
'el' 
>>>commonLetters("Purple","Apple")
'elp'
'''

def commonLetters(str1,str2):
    common = ""
    for i in str1:
        if i in str2 and i not in common:
            common += i
    return "".join(sorted(common))
In [3]:
# 3. WAP to echoWord() which repeats a word equal to the len of the word.
'''
>>> echoWord("Hi")
'HiHi'
>>> echoWord("hello")
'hellohellohellohellohello'
'''

def echoWord(str1):
    return str1 * len(str1)
In [4]:
# 4. WAP to check if two words are anagram. (Ignore case).
'''
>>> isAnagram("google","ggoole")
True
>>> isAnagram("google","gggole")
False
'''

def isAnagram(str1,str2):
    if sorted(str1)==sorted(str2):
        return True
    else:
        return False
In [5]:
# 5. WAP to check if a word has double consecutive letters.
'''
>>> hasDouble("Google")
True
>>> hasDouble("Microsoft")
False
'''

def hasDouble(str1):
    str1 = str1.lower()
    flag = False
    for i in str1[0:len(str1)-1]:
        index = str1.index(i)
        if i==str1[index+1]:
            flag = True
    return flag
In [19]:
# 6. WAP to find the missing side of a right angle triangle.
'''
Hint: Pythagoras Theorem: h**2  = a**2 + b**2
'''
import math
def missingSide():
    print("Enter 2 of 3 values for a right angled triangle")
    base = input("1. Enter the base: ")
    height = input("2. Enter the height: ")
    hypotenuse = input("3. Enter teh hypotenuse: ")
    try:
        if base == "":
            return math.sqrt(int(hypotenuse)**2 - int(height)**2)
        elif height == "":
            return math.sqrt(int(hypotenuse)**2 - int(base)**2)
        elif hypotenuse == "":
            return math.sqrt(int(base)**2 + int(height)**2)
    except:
        return "Invalid Input"