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]
print(l)

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

print(len(name))

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

print(l[len(l)-1])

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.

print(name[-1])
print(name[-2])

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] 
    print(letter) 
    i = i + 1

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

for char in name:
    print(char)
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'
print(s[0:4])
print(s[8:len(s)])
print(s[:4])
print(s[:len(s)])
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'
str[0]='T'

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
print(count)
Try it Yourself

The in operator in Python:

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

String comparison:

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

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

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

word='Orange'
if word < 'Apple': 
    print('Your word, ' + word + ', comes before Apple')
elif word > 'Apple': 
    print('Your word, ' + word + ', comes after Apple.')
else: 
    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

Loops

Lists