Introduction

Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.

Creating String

Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.

my_string = 'Hello'
my_string = "Hello"
my_string = '''Hello'''

# Triple quotes string can extend multiple lines
my_string = """Hello, welcome to
               the world."""

Accessing Characters

We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator (colon).

x = "Hello World!" 

# Output: 'llo World!'
print(x[2:])

# Output: 'He'
print(x[:2])

# Output: 'Hello Worl' 
print(x[:-2])

# Output: 'd!'
print(x[-2:]) 

# Output: 'llo Worl'
print(x[2:-2])

# Output: 'H'
print(str[0])

# Output: '!'
print(str[-1])

Modify String

Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Although deletion of entire String is possible with the use of a built-in del keyword. This is because Strings are immutable, hence elements of a String cannot be changed once it has been assigned. Only new strings can be reassigned to the same name.

my_string = 'Python'

# Not allowed.
# my_string[5] = 'a'

del my_string

String Concatenation

Joining of two or more strings into a single one is called concatenation. The + operator does this in Python. Simply writing two string literals together also concatenates them. The * operator can be used to repeat the string for a given number of times.

Writing two string literals together also concatenates them like + operator. If we want to concatenate strings in different lines, we can use parentheses.

str1 = 'Hello'
str2 ='World!'

# Using +
print('str1 + str2 = ', str1 + str2)

# Using *
print('str1 * 3 =', str1 * 3)

# Two string literals together
print('Hello' 'World!')    
    
# Using parentheses
s = ('Hello '
    'World')

Strings Formatting

Strings can be formatted with the use of format() method. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order.

# Default(implicit) order
default_order = "{}, {} and {}".format('IN','BL','SE')

# Output: IN, BL and SE
print(default_order)

# Order using positional argument
positional_order = "{1}, {0} and {2}".format('IN','BL','SE')

# Output: BL, IN and SE
print(positional_order)

# Order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='IN',b='BL',s='SE')

# Output: SE, BL and IN
print(keyword_order)

The format() method can have optional format specifications. They are separated from field name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space. We can also format integers as binary, hexadecimal etc. and floats can be rounded or displayed in the exponent format.

# Binary representation of Integers
String1 = "{0:b}".format(16) 

# Output: 10000
print(String1) 

# Exponent representation of Floats 
String1 = "{0:e}".format(165.6458) 

# Output: 1.656458e+02
print(String1) 

# Rounding off Integers 
String1 = "{0:.2f}".format(1/6) 

# Output: 0.17
print(String1)

An escape sequence starts with a backslash and is interpreted differently. If we use single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.

# using triple quotes
print('''He said, "What's there?"''')

# Escaping single quotes
print('He said, "What\'s there?"')

# Escaping double quotes
print("He said, \"What's there?\"")

Built-in Methods

Every item of data in a Python program is an object. Methods are similar to functions. A method is a specialized type of callable procedure that is tightly associated with an object. Like a function, a method is called to perform a distinct task, but it is invoked on a specific object and has knowledge of its target object during execution.

# Find first occurrence of character after given index
string = 'This + is + a + string'
print(string.find('+',7))    # 10

# Check if a string contains another string
str = "He is the best soccer player"
print("soccer" in str)       # True
print("football" in str)     # False

print((str.find("Ronaldo"))   # -1 if string is not found
print((str.find("Messi"))     # 0

# Length of string
len('Hellow Word')

# Split string at token
word = 'Hello, World'
# Splits at ',' 
print(word.split(', '))

# Remove whitespace and tab
s = '  abc  '
s.strip()

# Converts alphabetic characters to lowercase
s.lower()

# Swaps case of alphabetic characters.
s.swapcase()

# Converts alphabetic characters to uppercase.
s.upper()