Pyhton Strings

A string is a sequence of characters. You can access the characters one at a time with the bracket operator. The expression in brackets is called an index. The index indicates which character in the sequence you want to print.

name="Mr. X"
l = name[0]

Getting the length of a string using len() function:


To get the last letter of a string, you might try this:


Alternatively, you can use negative indices, which count backward from the end of the string. The expression l[-1] yields the last letter, l[-2] yields the second to last, and so on.


Traversing a  string with a loop:

One way to write a traversal is with a while loop:

i = 0
while i < len(name): 
    letter = name[i] 
    i = i + 1

One way to write a traversal is with a for loop:

for char in name:
Try it Yourself

String slices

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

s = 'Make Me Analyst'
Try it Yourself

Strings are immutable:

Strings are immutable in Python. It means you can’t change an existing string. Let’s try the below example:

str = 'Make Me Analyst'

If you run the above coce you will get an error like this: TypeError: ‘str’ object does not support item assignment
The reason for the error is that strings are immutable. g. The best you can do is create a new string that is a
variation on the original:

str = 'Make Me Analyst'
new_str='Hi! '+ str[8:len(str)]

This example concatenates a new first word onto a slice of the string and it has no effect on the original string.

Try it Yourself

Looping and counting

The following program counts the number of times the letter “M” appears in a string:

str = 'Make Me Analyst'
count = 0
for letter in str:
    if letter == 'M':
        count = count + 1
Try it Yourself

The in operator in Python:

str = 'Make Me Analyst'
a='Analyst' in str
b='x' in str
Try it Yourself

String comparison:

The comparison operators work on strings.  Following code checks if two strings are equal:

if word=='Analyst':
    print('Both are same!')

Some comparison operations are useful for putting words in alphabetical order:

if word < 'Apple': 
    print('Your word, ' + word + ', comes before Apple')
elif word > 'Apple': 
    print('Your word, ' + word + ', comes after Apple.')
    print('All right, Orange!!!')

Note: Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters

Try it Yourself