Inside the String
Explore the fundamentals of Python strings as collections of characters. Learn how to initialize strings, access individual characters using positive and negative indexing, extract slices, and modify strings through slicing and concatenation. Practice with example programs to reverse strings, shift characters, and test palindromes.
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:
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
String1is enclosed in single quotes''. - Line 4: The text of
String2is enclosed in double quotes"". - Line 7: The text of
String3andString4is enclosed in three single quotes''''''. - The last method also makes it easy to assign multiple lines of text to a string variable, like