You can learn about Strings in Python Programs with Outputs helped you to understand the language better.

Python Programming – Logical and Physical Line

The string is an ordered sequence of letters/characters. It is enclosed in single (“) or double (” “) or triple quotation(‘”) marks. The quotes are not a part of the string. They only tell the computer where the string constant begins and ends. They can have any character or sign, including space in between them.
‘Hello, World!’ is a string; it is so-called because it contains a ‘string’ of letters. You can identify strings because they are enclosed in quotation marks. If you are not sure which type of value it is, the interpreter can tell you.
>>> type(‘Hello, World!’)
<class ‘str’>
It is possible to change one type of value/variable to another type. It is known as type conversion or typecasting. The conversion can be done explicitly (the programmer specifies the conversion) or implicitly (the interpreter automatically converts the data type). An empty string contains no characters and has a length 0, represented by two quotation marks. The string with length 1 represents a character in Python. For example ‘a’, ‘b’, ‘c’ are strings of length one.
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. So, the following are invalid:

‘ 8 ‘ – ‘ 2 ‘
‘apples’/’easy’
‘third’*’first’

If you need to store numbers that may have calculations performed on them, do not make them a string. There’s a difference between the following two declarations:

a = 1
a = “1”

In the first line, the value 1 is a number. In the second line, it’s a string. The + operator works with strings, but it might not do what you expect; it performs concatenation, which means joining the strings by linking them end-to-end. For example:

str P Y T H O N
Positive index 0 1 2 3 4 5
Negative index -6 -5 -4 -3 -2 -1

first = ‘ Lakhan ‘
second = ‘ lal ‘
print(first + second)

The output of this program is Lakhanlal. The * operator also works on strings; it performs repetition. For example, ‘Save’*3 is ‘SaveSaveSave’. If one of the operands is a string, the other has to be an integer.
This use of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equivalent to 4+4+4, you expect ‘Save’*3 to be the same as ‘Sa- ve’+’Save’+’Save’. The plus ( + ) sign is the string concatenation operator, and the asterisk ( * ) is the repetition operator.
The string is a sequence of characters. You can access the characters one at a time with the bracket operator. An individual character in a string is accessed using a subscript (index). The subscript should always be an integer (positive or negative). It starts with 0. To access the first character of the string, consider the following:

>>> str = ‘PYTHON’
>>> print(str[0])
P

  • String indices are zero-based, i.e., the first character in a string has an index of 0.

The second statement selects character at number 0 from str and prints the character P. The expression in square brackets is called an index. The index indi¬cates which character in the sequence you want. The index is an offset from the beginning of the string, and the offset of the first letter is zero. To access the second character of the string, consider the follow¬ing:
>>> print(str[1])
Y
You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. If you try to access index out of the range or use the decimal number, you will get errors. >>> print(str[8])
IndexError: string index out of range
>>> print(str[1.5])

TypeError: string indices must be integers Alternatively, you can use negative indices, which count backward, i.e., from the end of the string to the beginning. The expression str[-l] yields the last letter, str [-2] yields the second last letter, and so on. To access the last character of the string, consider the following:
>>> print(str[-1])
N
To access the third last character of the string, consider the following:
>>> print(str[-3])
H
Strings in Python are stored by placing each charac-ter separately in contiguous locations as shown in Figure 6.4.

The index, also called subscript, is the numbered position of the letter in the string. In Python, indices begin from 0 onwards in the forward direction also called positive index, and from -1, -2, and so on in the backward direction, also called negative index. Positive subscript helps in accessing the string from the beginning. A negative subscript helps in accessing the string from the end.

  • The index is the numbered position of an alphabet in the given string.

You can access any character using <stringna- me>[<index>]. Index 0 or -ve n (where n is the length of the string) displays the first element. For example : str[0] or str[-6] will display the first element T’.
Subscript 1 or -ve (n-1) displays the second element. For example : str[l] or str[-5] will display the second element ‘Y’.
The built-in function len() returns the length of a string:
>>> str = “PYTHON”
>>> len(str)
6
Since the length of the string variable can be determined using len(<string>), you can say that:

(a) The first character of the string is at index 0 or -length. So in the example given in Figure 6.4, at index 0 or -6, the character stored is P.
(b) The second character of the string is at index 1 or -(length-1). So in the example given in Figure 6.4, at index 1 or -(6-1)= -5, the character stored is Y.
(c) The second last character of the string is at index (length-2) or -2. So in the example given in Figure 6.4, at index (6-2)= 4 or -2, the character stored is O.
(d) The last character of the string is at index (length-1) or -1. So in the example given in Figure 6.4, at index (6-1)= 5 or -1, the character stored is N.

Let’s Try

Write the output of the following code segments:

>>> name = ‘Abhishek’
>>> letter = name[l]
>>> name = ‘Abhishek’
>>> letter = name[l]
>>> print(letter)

Example
Accessing python string items.

# Access python string items
X = ‘ BPB PUBLICATIONS ‘
# positive Indexing
print (x[0])
print (x[1])
print (x[2])# Negative Indexing
print (x[-1])
print (x[-2])
print (x[-3])RUN
>>>
B
P
BS
N
O
>>>

Strings are Immutable

Strings are immutable means that the contents of the string variable cannot be changed after it is created. Let us understand the concept of immutability with the help of an example.
>>> greeting = ‘Hello, world!’
>>> greeting[0] = ‘J’
TypeError: ‘str’ object does not support item assignment The object in this case is the string, and the item is the character you tried to assign. Python does not allow the programmer to change a character in a string. As shown in the above example, greeting has the value ‘Hello, world!’. An attempt to replace ‘H’ in the string by ‘J’ displays a TypeError.
The reason for the error is that strings are immuta-ble, which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original:
>>> greeting = ‘Hello, world!’
>>> newgreeting = ‘J’ + greeting[1:]
>>> print (newgreeting)
Hello, world!
This example concatenates a new first letter to a slice (a part of a string specified by a range of indices) of greeting. It has no effect on the original string. You will study string slice later in this chapter. Python strings cannot be changed. Assigning a character to an indexed position in the string results in an error.

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

You cannot delete or remove characters from a string. This will cause an error because item assign-ment or item deletion from a string is not supported. Although deletion of the entire string is possible with the use of a built-in del keyword.
>>> mystring = ‘Hello’
>>> mystring ‘Hello’
>>> del my_string
Further, if you try to print the string, this will produce an error-“NameError: name ‘my_string’ is not defined” because String is deleted and is unavailable to be printed.
>>> mystring
You can assign a string to another string or an expression that returns a string using the assignment. For example,
>>> strl = ‘Teena’

Traversing a String

Traversing a string means accessing all the elements of the string one after the other by using the sub-script or index. The string can be traversed character-by-character using for loop or while loop. Example 3 demonstrates string traversal using for loop. In this program, each character of string “PY-THON” will be accessed one-by-one. In each iteration of for loop, the next character in the string str is assigned to the variable, i. The loop continues until no character is left.

Example
String traversal using for loop.

# String traversal using for loop
str = “PYTHON”
for i in str:
print(i)RUN
>>>
P
Y
T
H
O
N
>>>

Example
String traversal using while loop.

# String traversal using while loop
Str = “PYTHON”
i=0
while i < len(str):
print(str[i])
i = i+1
RUN
>>>
P
Y
T
H
O
N
>>>

The while loop traverses the string and displays each letter on a line by itself. The loop condition is i < len(str); so when i is equal to the length of the string, the condition becomes false, and the body of the loop is not executed. (See Figure 6.7).

Example
Finding the length of entered string .

# Program to find the length of entered string
while True:
s = input(‘Enter something : ‘)
if s == ‘quit’:
break
print(‘Length of the string is’, len(s))
print(‘Done’)RUN
>>>
Enter something: Hello PYTHON
The length of the string is 12
Enter something: WELCOME
The length of the string is 7
Enter something: quit
Done
>>>

In this program, you repeatedly take the user’s input and print the length of each input. You are providing a special condition to stop the program by checking if the user input is ‘quit’. If it is so, stop the program by breaking out of the loop and reach the end of the program. The length of the input string can be found out using the built-in len() function. (See Figure 6.8).

Example
Program to check length of a string with suitable message.

# Program to check length of a string with suitable message
while True:
s = input(‘Enter something : ‘)
if s == ‘quit’:
break
if len(s) < 3 :
print(‘Too small’)
continue
print(‘Input is of sufficient length’)RUN
>>>
Enter something: C
Too small
Enter something: Ca
Too small
Enter something: Cat
Input is of sufficient length
Enter something: Elephant
Input is of sufficient length
Enter something: quit
>>>

In this program, you accept input from the user, but you process the input string only if it is at least 3 characters long. So, you use the built-in len() function to get the length and if the length is less than 3, you skip the rest of the statements in the loop by using the continue statement. Otherwise, the rest of the statements in the loop are executed, doing any kind of processing you want to do here. (See Figure 6.9).

Example
Program to replace character in a string with a symbol.

# Python program to replace character in a string with a symbol input_string = str(input(“Enter a string : “))
st=input(“Enter a character you want to change in the entered string : “)
symbol = input(“Enter the symbol you want to replace with : “)
changed_str = inputstring.replace(st,symbol)
print(“Modified String is s “,changedstr)RUN
>>>
Enter a string: Hello
Enter a character you want to change in the entered string: e
Enter the symbol you want to replace with: @
Modified String is: H@llo
>>>

Example
The program accepts a string as input and prints “Yes” if the string is “yes” or “YES” or “Yes”, otherwise prints “No”.

# Program which accepts a string as input and print “Yes” or “No” inputstring = str(input(“Enter a string : “))
if input_string== ” yes ” or input_string== ” yes ” or input_string == ” yes ” :
print ( ” yes ” )
else:
print ( ” No ” )RUN
>>>
Enter a string: yes
Yes
>>>>>>
Enter a string: Hello
No
>>>

String Formatting

String formatting syntax has changed from Python 2 to Python 3.
Python 2 “%d %s” % (i, s)
Python 3 “{ } { }”.format(i, s)
Python 2 “%d/%d=%f” % (355, 113, 355/113)
Python 3 “{:d}/{:d}={:f}”.format(355,113, 355/113)
For example,
>>> “{ } comes before { }”.format(‘a’,’b’)
‘a comes before b’

num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
product = num1 * num2
print(‘The product of’, num1, ‘and’, num2. ‘is’, product)RUN
>>>
Enter first number: 5
Enter second number: 8
The product of 5 and 8 is 40
>>>

But program shown above is cumbersome. To accomplish the same thing, specify any variables to be interpolated in curly braces ({ }). Specify either a lowercase f or uppercase F directly before the opening quote of the string literal. This tells Python it is an f-string instead of a standard string. (See Figure 6.12).

num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
product = num1 * num2
print(f’The product of {numl} and {num2} is {product}’)RUN
>>>
Enter first number: 5
Enter second number: 8
The product of 5 and 8 is 40
>>>

The format( ) is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. Format string contains curly braces {} as placeholders or replacement fields which get replaced. It is separated from field name using colon(:). For example, you can left-justify <, right-justify > or center A a string in the given space. You can also format integers as binary, hexadecimal, etc, and floats can be rounded or displayed in the exponent format. You can use positional arguments or keyword arguments to specify the order. Figure 6.13 demonstrates different ways of string formatting.

Example
Program for the formatting of string.

# Program for formatting of strings

# Default order
str1 = “{} {} {}”.format(‘Work’, ‘Is’, ‘Worship’)
print(“String in default order: “)
print(str1)

# Positional Formatting
str1 = “{1} {0} {2}”.format(‘Work’, ‘Is’, ‘Worship’)
print(“\nString in Positional order: “)
print(str1)

# Keyword Formatting
str1 = “{1} {f} {g}”.format(g = ‘Work’, f = ‘Is’, 1 = ‘Worship’)
print(“\nString in order of Keywords: “)
print(str1)

# Formatting of Integers
str1 = “{0:b}”.format(12)
print(“\nBinary representation of 12 is “)
print(str1)

# Formatting of Floats
str1 = “{0:e}format(154.6347)
print(“\nExponent representation of 154.6347 is “)
print(str1)

# Rounding off Integers
str1 = “{02f}”.format(1/4)
print(“\nOne-fourth is : “)
print(str1)

# String alignment
str1 = “|{:<10}|{:^10}|{:>10}|”.format(‘Work’,’Is’,’Worship’)
print(“\nLeft, center and right alignment with Formatting: “)
print(str1)

RUN
>>>
String in default order:
Work Is Worship

String in Positional order:
Is Work Worship

String in order of Keywords:
Worship Is Work

The binary representation of 12 is
1100

Exponent representation of 154.6347 is
1.546347e + 02

One-fourth is :
0.25

Left, center, and right alignment with Formatting:
|Work | Is | Worship|
>>>

Let’s Try

Write the output of the following Python codes:

# Iterate Python String
str = ‘SCHOOL’
for a word in str:
print(“Letters are: “, word)
# Iterate Python String
str =”SCHOOL”
for word in range(len(str)):
print(“Letters at index {0} is = {l}”.for-
mat(word, str[word]))

Leave a Reply

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