String is an ordered collection of characters, and each character is stored in a contiguous memory location. Strings are used to represent data of the same types. In Python, strings are immutable data types. Individual characters are accessed through the indices representing their position. In python any data enclosed within quotes is treated as a string. The data can be a number, letter, or a special character.

String Operations in Python

Consider the example,

str = “test string”

print(‘str=  ‘, str)

The contents of the string variable will be displayed as,

Output:

str = test string

Few other examples:

Capitalize

capStr= str.capitalize() 

print(‘capStr = ‘, capStr)

Here the function capitalize() will convert the first character of the string into uppercase  and assign it to a new variable capStr.

Output:     

capStr = Test string

Count

countT = str.count(‘t’)

print(countT)

The function count() will return the number of occurrences of ‘t’ in the given string.

Output: 3

Find

findstr =  str.find(‘str’)

print(findstr)

Locates the first occurrence of the sub-string ‘str’ in the given string.

Output: 5 

As the string ‘test string’ has 11 character positions and the indices start from 0 onwards, the substring ‘str’ has the first occurrence at the fifth index position.

checkStr = ‘good’ in str

print(checkStr) 

Checks if the substring ‘good’ is present in the string variable str.

Output : False

isdigit

# Numeric digit 6 in Hindi / Devnagari

quantity = “६” 

checkIsDigit = quantity.isdigit()

print(checkIsDigit)

isdigit() return True if all characters in the string are digits and there is at least one character, False otherwise.

Output : True

isdecimal

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

rate = “६”

checkIsDecimal = rate.isdecimal()

print(checkIsDecimal)

Output : True