2️⃣ String

  • Python string is collection of one or more characters and used to represent textual data.

  • There is no character datatype in python to represent characters.

  • Strings are immutable data structures, that means once defined, they can’t be changed.

  • We can create strings using single, double or triple quotes.

  • Strings are nothing but array of characters.

  • We can also do multiline comment in code with help of strings.

💻 Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# string examples
first_name='sachin'
roll_num='104'

# string definition using double quotes
school_name="Vision English School"

# string definition using triple quotes
address="""House No.73,Bakers Street,
                  Room No.D1405,Near Telephone Exchange,
                  Mumbai"""

String Slicing:

  • We can slice strings and get required part of string.

  • We can access each characters of a string using index enclosed with square brackets.

  • String indexing always starts from zero.

  • Slicing syntax: string[start:end:step] where,

    • start: Starting index where slicing of string starts.

    • end: End index where slicing of string ends.

    • step: Optional argument, which determines increment between each index.

Slicing with positive indicing:

  • Lets slice string using positive indices.

💻 Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
mystr = 'abcdefgh'
# Slicing Syntax:  string[start:end:step]
print("Lets slice string: ", mystr)
print("1] Print every character using mystr[:]:")
print('Output->', mystr[:])
print("2] Slice first index character using mystr[0]:")
print('Output->',mystr[0])
print("3] Slice 3rd index character using mystr[3]:")
print('Output->',mystr[3])
print("4] Print every character from 3rd index usign mystr[3:]:")
print('Output->',mystr[3:])
print("5] Slice first 4 characters from string usign mystr[:4]:")
print('Output->',mystr[:4])
print("6] Slice from 2nd character to 5th character using mystr[2:5]:")
print('Output->',mystr[2:5])
print("Lets understand the step argument..")
print("1] Print everything with step argument 1 using mystr[::1](skip nothing):")
print('Output->',mystr[::1])
print("2] Print everything with step argument 2 using mystr[::2](skip 1 character):")
print('Output->',mystr[::2])
print("3] Print everything with step argument 3 using mystr[::3](skip 2 characters):")
print('Output->',mystr[::3])

✅ Output:

Lets slice string:  abcdefgh
1] Print every character using mystr[:]:
Output-> abcdefgh
2] Slice first index character using mystr[0]:
Output-> a
3] Slice 3rd index character using mystr[3]:
Output-> d
4] Print every character from 3rd index usign mystr[3:]:
Output-> defgh
5] Slice first 4 characters from string usign mystr[:4]:
Output-> abcd
6] Slice from 2nd character to 5th character using mystr[2:5]:
Output-> cde
Lets understand the step argument..
1] Print everything with step argument 1 using mystr[::1](skip nothing):
Output-> abcdefgh
2] Print everything with step argument 2 using mystr[::2](skip 1 character):
Output-> aceg
3] Print everything with step argument 3 using mystr[::3](skip 2 characters):
Output-> adg

💻 Example:

1
2
3
4
5
6
mystring = "Welcome to TechnoDexterous"
print(mystring[0])
print(mystring[:])
print(mystring[0:7])
print(mystring[11:])
print(mystring[3:10])

✅ Output:

W
Welcome to TechnoDexterous
Welcome
TechnoDexterous
come to

Slicing with negative indicing:

  • Negative indexing starts from end of the string towards start of string (from right to left side of string).

  • Negative indexing always starts with from -1, which is the last character of the string.

  • Below is the example of same string sliced with negative indices.

💻 Example:

1
2
3
print(mystring[-1])
print(mystring[-9:])
print(mystring[-15:-9])

✅ Output:

s
Dexterous
Techno

Slicing with step argument:

  • Step is optional argument, which determines increment between each index.

💻 Example:

1
2
3
4
5
6
number_string = "0123456789"
print(number_string[::2])
print(number_string[::3])
print(number_string[::4])
print(number_string[:6:2])
print(number_string[2:9:2])

✅ Output:

02468
0369
048
024
2468
  • Similarly we can use negative step argument to reverse the string.

💻 Example:

1
2
number_string = "0123456789"
print(number_string[::-1])

✅ Output:

9876543210

String Operations:

We can also apply different operators with strings. They are useful in modifying string structure to form new string.

Concatenation (+):

  • plus operator joins or concatenate multiple strings together to from new string.

💻 Example:

1
2
3
4
a="One"
b="Two"
c="Three"
print(a+b+c)

✅ Output:

OneTwoThree

Multiplication(*):

  • String repetition is perfromed using ‘*’ operator. If the string multiplied with ‘n’ number, we will get concatenated form of same string n times as an output.

💻 Example:

1
2
3
print(a*1)
print(b*2)
print(c*3)

✅ Output:

One
TwoTwo
ThreeThreeThree

Note: You can add multiple strings with eachother and get the concatenated string but you can’t multiply two strings with eachother, it will give SyntaxError.

💻 Example:

1
2
3
a = 'one'
b = 'two'
print(a*b)

✅ Output:

TypeError: can't multiply sequence by non-int of type 'str'

String Methods:

Methods are nothing but predefined functions which operates on strings and perfroms strings transformations and provide desired string information. Lets learn them one by one.

  • len( ) : This method returns length of strings i.e. number of characters present in string. Spaces present in string are also considered while calculating the length.

💻 Example:

1
2
a = 'hello guys'
print(len(a))

✅ Output:

10
  • upper( ) : It upper cases the characters in string.

  • lower( ) : It lower cases the characters in string.

  • capitalize( ) : It converts first character of string to upper case.

💻 Example:

1
2
3
4
a = 'abc'
print(a.upper())
print(a.lower())
print(a.capitalize())

✅ Output:

ABC
abc
Abc
  • islower( ), isupper( ) : returns True if all characters in string are lower case, upper case respectively.

💻 Example:

1
2
3
4
5
6
a = 'abc'
print(a.isupper())
print(a.islower())
b = 'ABC'
print(b.isupper())
print(b.islower())

✅ Output:

False
True
True
False
  • isspace( ) : returns True if string contains all spaces, otherwise returns False.

💻 Example:

1
2
3
4
c = ' a b c '
print(c.isspace())
d = '   '
print(d.isspace())

✅ Output:

False
True
  • strip( ) : It trims spaces present in string from both left and right sides.

  • lstrip( ) : It trims spaces present in string from left side.

  • rstrip( ) : It trims spaces present in string from right side.

💻 Example:

1
2
3
4
mystring = ' lets learn python '
print(mystring.strip())
print(mystring.lstrip())
print(mystring.rstrip())

✅ Output:

lets learn python
lets learn python
 lets learn python
  • count( ): It returns count of character or word present in string, when particular word or character passed to this method.

💻 Example:

1
2
3
4
mystring = ' lets learn python '
print(mystring.count('l'))
print(mystring.count('le'))
print(mystring.count('python'))

✅ Output:

2
2
1
  • isapha( ) : returns True if string contains only alphabets (A-Z, a-z). Underscores and spaces are not alphabets.

  • isnumeric( ) : It returns True if all characters in string are numbers, otherwise returns False.

  • isalnum( ) : returns True if all characters in string are alphanumeric( A-Z, a-z, 0-9 ) i.e alphabets and numbers. Underscores and spaces are not alphanumeric characters.

💻 Example:

1
2
3
4
5
6
alpha_string = 'TechnoDexterous'
print(alpha_string.isalpha())
num_string = '12345'
print(num_string.isnumeric())
alphanum_string = 'PinCode411041'
print(alphanum_string.isalnum())

✅ Output:

True
True
True
  • endswith( ), startswith( ): returns True if the string ends, starts with specified character or word respectively.

💻 Example:

1
2
3
4
mystring = 'I will learn python 100%'
print(mystring.startswith('I'))
print(mystring.endswith('100'))
print(mystring.endswith('100%'))

✅ Output:

True
False
True
  • replace( ) : It replaces the word or character in string with specified word or character.

💻 Example:

1
2
3
mystring = 'I will learn python 100%'
print(mystring.replace('100', '200'))
print(mystring.replace('I','We'))

✅ Output:

I will learn python 200%
We will learn python 100%
  • split( ) : It splits the string at the specified separator (default ‘space’) into a list. It is used to convert string data type into list.

💻 Example:

1
2
3
4
mystring = 'I will learn python 100%'
print(mystring.split())
num_string = '1,2,3,4,5,6,7'
print(num_string.split(','))

✅ Output:

['I', 'will', 'learn', 'python', '100%']
['1', '2', '3', '4', '5', '6', '7']

Special Character Role:

Strings behaves differently with some special characters like ( \n amd \t).

Sr.

Special Char

Example

1

next line( \n )

It puts the characters to next line.

2

tab( \t )

It puts tab in string.

Lets see examples of strings containing special characters..

💻 Example: Use of \n character in string.

1
2
mystr = 'Hello Friends \nGood Morning \nWelcome to TechnoDexterous'
print(mystr)

✅ Output:

Hello Friends
Good Morning
Welcome to TechnoDexterous

💻 Example: Use of \t character in string.

1
2
mystr = 'One\tTwo\tThree\tFour'
print(mystr)

✅ Output:

One    Two     Three   Four

Thus we can display strings differently with the usage of special characters in string.

String Formatting:

String formatting plays important role when you want to consider variable values inside the string. Without string formatting the print statement becomes lengthy or unoptimized.

💻 Example:

1
2
3
4
5
first_name='Virat'
last_name='Kohli'
print('The player name is:')
print(first_name)
print(last_name)

✅ Output:

The player name is:
Virat
Kohli

Above example uses print statement 3 times and the output also got displayed in 3 lines. We can display above output in a single line with the help of string formatting. Lets see the ways of string formatting one by one:

1) format() method:

We can use .format method to format the variables to be displayed inside string at different places.

💻 Example:

1
2
3
4
first_name='Virat'
last_name='Kohli'
final_str='The player name is:{} {}'.format(first_name,last_name)
print(final_str)

✅ Output:

The player name is:Virat Kohli

# Lets consider more examples.

💻 Example:

1
2
3
4
5
6
7
a=10
b=20
addition=a+b
str1='We have two numbers:{},{}'.format(a,b)
str2='Their sum is:{}'.format(addition)
print(str1)
print(str2)

✅ Output:

We have two numbers:10,20
Their sum is:30

You can also pass the numbers to curly braces respective to the variables passed in format() method. This helps to repeat the variable value in different places in the same string.

💻 Example:

1
2
3
4
5
6
result1='passed'
result2='failed'

#lets format string
str_from='Shubham:{0},Raj:{1},Sima:{0},Ram:{0}'.format(result1,result2)
print(str_from)

✅ Output:

Shubham:passed,Raj:failed,sima:passed,Ram:passed
  • We can add padding to a digits easily:

💻 Example:

1
2
3
4
# padding a 3 digit number with zero.
for num in range(5):
    str_form='The number is:{:03}'.format(num)
    print(str_form)

✅ Output:

The number is:000
The number is:001
The number is:002
The number is:003
The number is:004
  • We can also display a particular number with required decimal point values.

1
2
3
4
float_num=3.5214432
# Lets print it up to two decimal points
str_form='{:.2f}'.format(float_num)
print(str_form)

✅ Output:

3.52
  • Lets print out large number with commas.

1
2
str_form='1 lakh equals:{:,}'.format(10**5)
print(str_form)

✅ Output:

1 lakh equals:100,000

2) format(f) string method:

It is another way of string formatting which is more simpler than previous one. You can simply use ‘f’ character before the string starts and use variable names directly inside curly braces whenever you want.

💻 Example:

1
2
3
4
5
6
7
8
9
a=10
b=20
str_form=f'Number {a} is less than number {b}'
print(str_form)

# lets calculate their sum

str2=f'Their sum is:{a+b}'
print(str2)

✅ Output:

Number 10 is less than number 20
Their sum is:30

Be prepared with below questions prior to your interview !

Frequently asked Interview Questions
  1. What are strings in python?

  2. Can you change a string once it’s created?

  3. What is string formatting and its types?

  4. What is string slicing?

  5. What is string concatenation?

  6. What different methods a string support?

  7. Can we convert a string into integer?

  8. Explain split() method.