(1) What Is A String Datatype?

  • A String is a collection of a sequence of characters.
  • A String can contain Alphabetic, Numeric, or Special characters.
  • A String variable is enclosed within a single(”) or double quote(“”).
  • A String type in Python is of the ‘str’ type.

Example-1

name = 'Subrat Kumar Sahoo'
print(name)
Subrat Kumar Sahoo

Example-2

password = "hallo@123"
print(password)
hallo@123

Example-3

country = 'India'
print(country)
India

(2) How To Check Existence Of A Character Or A Sub-string In A String?

  • You can use ‘in’ keyword to check the existence of a sub-string in a string.

Example-1

"pass" in "you have passed the exam !!"
True

Example-2

"fail" in "you have passed the exam !!"
False

(3) How To Check Non Existence Of A Character Or A Sub-string In A String?

  • You can use ‘not in’ keyword to check the existence of a sub-string in a string.

Example-1

"Priya" not in "Subhada, Arpita, Abhispa, Anuradha"
True

Example-2

"Abhispa" not in "Subhada, Arpita, Abhispa, Anuradha"
False

(4) Converting String To Int or Float Datatype.

  • If a number is enclosed under quotations then it is considered as a string.
  • That string you can convert into a number again.
  • You can’t convert any string into a number.

Example-1

num = "145"
num = int(num)
print(type(num))
print(num)
<class 'int'>
145

Example-2

num = 'ABC'
int(num)
ValueError                                Traceback (most recent call last)
Input In [14], in <cell line: 2>()
      1 num = 'ABC'
----> 2 int(num)

ValueError: invalid literal for int() with base 10: 'ABC'

(5) How To Slice A String ?

  • string_name[starting_index : finishing_index : character_iterate]
  • starting_index: Start Index position from where you want to slice.
  • finishing_index: End Index position from where you want to end.
  • character_iterate: Number of indexes to jump while slicing.

Example-1

string = "Hello How Are You Doing?"
string[0:5]
'Hello'

Example-2: Jumps One Step

string = "Hello How Are You Doing?"
string[0:10:1]
'Hello How '

Example-3: Jumps Two Steps

string = "Hello How Are You Doing?"
string[0:10:2]
'HloHw'

Example-4: Negative indicates Starts From End

string = "Hello How Are You Doing?"
string[10:0:-1]
'A woH olle'

(5) How Would you confirm that 2 strings have the same identity?

  • Here the same identity means, both the string will have the same value and address.
  • The ‘is’ operator is used to check whether the variable is having same value and address.
  • Whare as “==” operator is used to check only the values of the variable.

Example-1

math = [95,98]
english = math
science = [95,98]

print(math == english) 
print(math is science) 
True
False

Example-2

animals           = 'python'
more_animals      = animals
even_more_animals = 'python'

print(animals == more_animals) 
print(animals is more_animals) 
print(animals == even_more_animals)
print(animals is even_more_animals)
True
True
True
True

(6) How Would You Check If Each Word In A String Begins With A Capital Letter?

  • The istitle() function checks if each word is capitalized.

Example-1

print( 'Hello World'.istitle() ) 
print( 'The emperor'.istitle() )
print( 'sweet Corn'.istitle() ) 
True
False
False

(7) Find The Index Of The First Occurrence Of A Substring In A String.

  • find() and index() methods are used to get the index of the substring inside a string.
  • find() returns -1 if the substring is not found.
  • index() will throw a ValueError if the substring is not found.

Example-1

print('My name is Subrat'.find('Subrat'))
print('What is your name?'.find('Abhispa'))
11
-1

Example-2

print('My name is Subrat'.index('Subrat'))
print('What is your name?'.index('Abhispa'))
11
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [81], in <cell line: 2>()
      1 print('My name is Subrat'.index('Subrat'))
----> 2 print('What is your name?'.index('Abhispa'))

ValueError: substring not found

(8) Count The Total Number Of Characters In A String.

  • len() will return the length of a string.

Example-1

string = "Hello How Are You Doing?"
len(string)
24

(9) Count The Number Of A Specific Character In A String.

  • count() will return the number of occurrences of a specific character.

Example-1

string = "How old Are You ?"
string.count('o')
3

Example-2

string = "How old Are You ?"
string.count('How')
1

(10) Capitalize The First Character Of A String.

  • capitalize() function is used to do this.

Example-1

string = 'good morning!!'
string.capitalize()
'Good morning!!'

(11) What Is An f-string And How Do You Use It?

  • f-strings make string interpolation really easy. Using f-strings is similar to using format().
  • F-strings are denoted by an f before the opening quote.

Example-1

name = "Subhada"
age = "23"
print(f'My name is {name} and I am {age} years old.')
My name is Subhada and I am 23 years old.

(12) Interpolate A Variable Into A String Using format().

  • format() is similar to using an f-string.
  • Though in my opinion, it’s less user friendly because variables are all passed in at the end of the string.

Example-1

name = "Subhada"
age = "23"
'My name is {} and I am {} years old.'.format(name,age)
My name is Subhada and I am 23 years old.

(13) Check If A String Contains Only Numbers.

  • isnumeric() returns True if all characters are numeric.

Example-1

string = "000000008"
string.isnumeric()
True

Example-2

string = "0.00000008"
string.isnumeric()
False

(14) Split A String On A Specific Character.

  • The split() function will split a string on a given character or characters.

Example-1

string = "Abhispa I Love You !!"
words = string.split(' ')
words
['Abhispa', 'I', 'Love', 'You', '!!']

Example-2

string = "subratsahoo@gmail.com"
words = string.split('@')
words
['subratsahoo', 'gmail.com']

(15) Check If A String Is Composed Of All Lower Case Characters.

  • islower() returns True only if all characters in a string are lowercase.

Example-1

string = 'i am in lower case'
string.islower()
True

Example-2

string = 'I am in Upper case'
string.islower()
False

(16) Check If The First Character In A String Is Lowercase.

  • islower() Function can be used to do this.

Example-1

string = 'Hello World!!'
string[0].islower()
False

Example-2

string = 'hello World!!'
string[0].islower()
True

(17) Can An Integer Be Added To A String In Python?

  • In some languages this can be done but python will throwTypeError

Example-1

'Hundred' + 100
TypeError                                 Traceback (most recent call last)
Input In [106], in <cell line: 1>()
----> 1 'Hundred' + 100

TypeError: can only concatenate str (not "int") to str

(18) Reverse The String “hello world”

  • We can do this by using String slicing operation.

Example-1

string = "hello world"
string[::-1]
'dlrow olleh'

(19) Join A List Of Strings Into A Single String, Delimited By Hyphens.

  • join() function can join characters in a list with a given character inserted between every element.

Example-1

'-'.join(['a','b','c'])
'a-b-c'

Example-2

'-'.join(['Subrat','Subhada','Abhispa'])
'Subrat-Subhada-Abhispa'

(20) Uppercase Or Lowercase An Entire String

  • upper() and lower() return strings in all upper and lower cases.

Example-1

string = "i love you darling !!"
string.upper()
'I LOVE YOU DARLING !!'

Example-2

string = "SAVE THE TREE !!"
string.lower()
'save the tree !!'

(21) Uppercase First And Last Character Of A String.

  • We can use string slicing to do this operation.

Example-1

programming = "Python"
programming[0].upper() + programming[1:-1] + programming[-1].upper()
'PythoN'

(22) When Would You Use splitlines()?

  • splitlines() splits a string on line breaks.

Example-1

sentence = "It was a stormy night\nThe house creeked\nThe wind blew."
sentence.splitlines()
['It was a stormy night', 'The house creeked', 'The wind blew.']

(23) Check If A String Contains Only Characters Of The Alphabet.

  • isalpha() returns True if all characters are letters.

Example-1

"Subhada@1".isalpha()
False

Example-2

"Abhispa".isalpha()
True

(25) Replace All Instances Of A Substring In A String.

  • replace() method is used replace the substring from a parent string.

Example-1

sentence = "A mother is your first friend, your best friend, your forever friend."
sentence.replace('mother', 'father')
'A father is your first friend, your best friend, your forever friend.'

(26) Return The Minimum Character In A String.

  • Capitalized characters and characters earlier in the alphabet have lower indexes.
  • min() will return the character with the lowest index.

Example-1

min('subhada')
a

Example-2

min('Subhada')
S

(27) Check If All Characters In A String Are Alphanumeric.

  • Alphanumeric values include letters and integers.

Example-1

print("Subhada@1".isalnum())
print("Subhada1".isalnum())
print("111Subhada".isalnum())
print("111Subhada.".isalnum())
False
True
True
False

(28) Remove Whitespace From The Left, Right Or Both Sides Of A String.

  • lstrip()rstrip() and strip() remove whitespace from the ends of a string.

Example-1

string = "  'string of whitespace'    "
print(string.lstrip())
print(string.rstrip())
print(string.strip())
'string of whitespace'    
  'string of whitespace'
'string of whitespace'

(29) Check If A String Begins With Or Ends With A Specific Character?

  • startswith() and endswith() check if a string begins and ends with a specific substring.

Example-1

string = "Subhada I Love You !!"
print(string.startswith('Subhada'))
print(string.endswith('Subhada'))
True
False

(30) Check If All Characters Are Whitespace Characters.

  • isspace() only returns True if a string is completely made of whitespace.

Example-1

print(''.isspace()) 
print(' '.isspace()) 
print('   '.isspace()) 
print(' the '.isspace()) 
False
True
True
False

(31) Capitalize The First Character Of Each Word In A String.

  • title() will capitalize each word in a string.

Example-1

'once upon a time'.title()
'Once Upon A Time'

(32) Concatenate Two Strings.

  • The additional operator (+) can be used to concatenate strings.

Example-1

'string one' + ' ' + 'string two' 
'string one string two'

(33) Give An Example Of Using The Partition() Function.

  • partition() splits a string on the first instance of a substring.
  • A tuple of the split string is returned without the substring removed.

Example-1

string = "Hello how are you doing ? are you fine ?"
string.partition('are')
('Hello how ', 'are', ' you doing ? are you fine ?')

(34) What Does It Mean For Strings To Be Immutable In Python?

  • Once a string object has been created, it cannot be changed.

  • Modifying” that string creates a whole new object in memory.

  • We can prove it by using the id() function.

Example-1

proverb = 'Rise each day before the sun'
print( id(proverb) )
2464429816368
proverb = 'Rise each day before the sun' + ' if its a weekday'
print( id(proverb_two) )
2464429441744

Note:

  • Concatenating ‘ if its a weekday’ creates a new object in memory with a new id.
  • If the object was actually modified then it would have the same id

(35) Does Defining A String Twice (associated with 2 different variable names) Create One Or Two Objects In Memory?

  • No
  • Because, If you are creating same string twice it won’t create a new memory location.
  • It will only refer to the same memory location.

Example-1

girl = "Subhada"
girl_friend = "Subhada"

print(id(girl))
print(id(girl_friend))
2464428575664
2464428575664

(36) Give An Example Of Using maketrans() and translate().

  • maketrans() creates a mapping from characters to other characters. 
  • translate() then applies that mapping to translate a string.

Example-1

mapping = str.maketrans("abcs", "123S")
"abc are the first three letters".translate(mapping)
'123 1re the firSt three letterS'

(37) Remove Vowels From A String

  • One option is to iterate over the characters in a string via list comprehension.
  • If they don’t match a vowel then join them back into a string.

Example-1

string = "Hello World !!"
vowels = ('a','e','i','o','u')
''.join(x for x in string if x not in vowels)
'Hll Wrld !!'

(38) When Would You Use rfind()?

  • rfind() is like find() but it starts searching from the right of a string and return the first matching substring.

Example-1

story = 'The price is right said Bob. The price is right.'
story.rfind('is')
39

(39) Sort A String Based On Ascii Value.

  • By using sing join() + sorted() we can solve this problem.

Example-1

sorted("ieyfgaecabga")
['a', 'a', 'a', 'b', 'c', 'e', 'e', 'f', 'g', 'g', 'i', 'y']
''.join(sorted("ieyfgaecabga"))
'aaabceefggiy'

Example-2

string = "Subrat"
''.join(sorted(string))
'Sabrtu'

(40) Count The Number Of Vowels In A String.

  • We can solve this using a for loop.

Example-1

string = "Hello World !!"
vowels = set('aeiouAEIOU')
count = 0
for i in string:
    if i in vowels:
        count = count +1
3

(41) Remove Numerical Values From A String

  • We can use isdigit() method to solve this problem.

Example-1

string = "hello@123"
result = ''.join([i for i in string if not i.isdigit()])
result
'hello@'

(42) Check If A String Is A Palindrome

  • We can reverse the string and check.

Example-1

string = "Hello"
reverse = string[::-1]
if string == reverse:
    print('Palimdrome')
else:
    print('Not Palimdrome')
Not Palimdrome

Example-2

string = "radar"
reverse = string[::-1]
if string == reverse:
    print('Palimdrome')
else:
    print('Not Palimdrome')
Palimdrome

Leave a Reply

Your email address will not be published. Required fields are marked *