Search⌘ K
AI Features

Inside the String

Explore the fundamentals of Python strings, including initialization with quotes, indexing, slicing, and modification techniques. Learn to manipulate strings through practical exercises such as reversing characters, shifting them, and checking for palindromes. Gain confidence using string functions and handling inputs of any length.

Collection

A collection is a general term used to group multiple values into a single unit. We use collections all the time in the real world―a book is a collection of pages, a train is a collection of train cars, and a wardrobe is a collection of clothes.

String

A string is a collection of characters, mostly treated as a single unit. A string is used to store text values like a name, address, message, etc.

Initializing the string

There are various ways to initialize a string in Python. The following program demonstrates these methods:

Python 3.10.4
String1 = 'String1 in Single Quotes'
print(String1)
String2 = "String2 in Double Quotes"
print(String2)
String3 = '''String3 in Three Single Quotes'''
print(String3)
String4 = '''String4 Three quotes
allow
multi-line'''
print(String4)

There are a few new things that we need to understand in the code above. Here are three ways to initialize a string variable:

  • Line 1: The text of String1 is enclosed in single quotes ' '.
  • Line 4: The text of String2 is enclosed in double quotes " ".
  • Line 7: The text of String3 and String4 is enclosed in three single quotes ''' '''.
  • The last method also makes it easy to assign multiple lines of text to a string variable, like in String4 in lines 10–12. This isn’t possible in the other two methods.

Accessing the characters in a string

Python allows us to access individual characters inside a string through an ...