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.
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.
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 'h' x[:2] 'he' Reverse a string x[::-1] 'olleh'
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'
String can be joined with another string using '+' operator.
"a" + "bcd" 'abcd'
String objects can repeat its value when multiplied with an integer.
x = "abc" * 3 print(x) 'abcabcabc'
# Functions working on case of string x = "indIA Is GReat"
'india is great'
'INDIA IS GREAT'
'India is great'
'INDia iS grEAT'
'india is great'
x = 'India is great'
'IndiT is greTt'
Boolean string functions¶
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 = '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
# 1. WAP to find is a given string starts with a vowel. ''' >>> startsWithVowel("Apple") True >>> startsWithVowel("banana") False ''' def startsWithVowel(str1): if str1 in "aeiouAEIOU": return True return False
# 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))
# 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)
# 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
# 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
# 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"