A string in Python is a sequence of characters. Each character in a string has an index that specifies its position in the string. Indexing starts at 0, so the index of the first character is 0, the index of the second character is 1, and so forth. The index of the last character in a string is 1 less than the number of characters in the string.
The bracket operator selects a single character from a string.
>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print(letter)
a
Strings can be enclosed in single quotes ('...') or double quotes ("...") with the same result. 'banana' and "banana" are the same.
You can also use negative numbers as indexes, to identify character positions relative to the end of the string. The index -1 identifies the last character in a string, -2 identifies the next to last character, and so on.
>>> s[-1]
n
>>> s[-2]
o
Strings can be concatenated with the + operator
>>> 'man'+'go'
'mango'
Strings can be repeated with the * operator
>>> 'go'*3
'gogogo'
The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
Program (substring.py)
This program finds a substring in a string.
string = input('Enter a sentence: ')
word = input('Enter a word: ')
if word in string:
print('substring found')
else:
print('substring not found')
Output
Enter a sentence: sparse is better than dense Enter a word: better substring found
A segment of a string is called a slice. To access slice, use the square brackets for slicing along with the index. Following is a simple example:
>>> s = "CBSE Python"
>>> print(s[0:7])
CBSE Py
>>> print(s[5:11])
Python
If you omit the first index (before the colon), the slice starts at the beginning of the string.
>>> print(s[:7])
CBSE Py
If you omit the second index, the slice goes to the end of the string.
>>> print(s[5:])
Python
Indices may also be negative numbers, to start counting from the right.
>>> print(s[-2:])
on
>>> print(s[:-2])
CBSE Pyth
>>> print(s[-5:-2])
yth
Extended Slicing
You can also use the step value in slicing. Syntax is given below:
string[start:end:step]
>>> text = 'ABCDEFGHIJK'
>>> text[::2]
'ACEGIK'
>>> text[1::2]
'BDFHJ'
>>> text[:4:2]
'AC'
To reverse a string use negative step
>>> text[::-1]
'KJIHGFEDCBA'
Strings in Python are immutable, which means their characters cannot be changed. The following code shows an example:
myname = 'Alax'
>>> myname[2]='e'
Traceback (most recent call last):
File "<pyshell#38>", line 1, in
myname[2]='e'
TypeError: 'str' object does not support item assignment
The len() function returns the number of characters in a string :
>>> fruit = 'banana'
>>> len(fruit)
6
Individual character of string can be accessed using index number. One way to access each individual characters in a string is to use a while statement:
fruit = 'banana'
index = 0
while index < len(fruit):
letter = fruit[index]
print (letter)
index = index + 1
This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed.
Output:
b a n a n a
Using an index to traverse a set of values is so common that Python provides an alternative, simpler syntax--the for loop:
fruit = 'banana'
for letter in fruit:
print (letter)
Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left. if we run the above code the output will be like :
Output:
b a n a n a
Program (count_letter.py)
This program counts the number of times the letter 's’ appears in a string.
count = 0
# Get a string from the user.
my_string = input('Enter a sentence: ')
# Count the letter s.
for ch in my_string:
if ch == 's' or ch == 'S':
count += 1
# Print the result.
print('No. of s in sentence are ', count)
Output:
Enter a sentence: sparse is better than dense. No. of s in sentence are 4
The comparison operators work on strings. To see if two strings are equal:
if word == 'banana':
print('All right, bananas.')
Other comparison operations are useful for putting words in alphabetical order:
Program (comparison.py)
word = input('Enter a fruit: ')
if word < 'banana':
print(word + ' comes before banana.')
elif word > 'banana':
print(word + ' comes after banana.')
else:
print('All right, bananas.')
Output
Sample Run#1
Enter a fruit: apple apple comes before banana.
Sample Run#2
Enter a fruit: mango mango comes after banana.
Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so:
Pineapple comes before banana.
A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison.