~2 min read · Updated Jul 18, 2025

Defining Strings in Python


Strings are defined using single (' ') or double (" ") quotes and are of type str. For multi-line text, triple quotes (''' ''' or """ """) can be used.


Strings are immutable, meaning their contents cannot be changed after creation.



my_str = "Python"
print(type(my_str))  # Output: <class 'str'>

Core Features of Strings


  • Indexing: Access individual characters by position.
  • Slicing: Extract specific portions using start:end syntax.
  • Length: Use len() to count characters.
  • Repetition: Use * to repeat strings.
  • Concatenation: Use + to join strings.

Examples:



text = "Python"
print(text[0])           # Output: 'P'
print(text[1:4])         # Output: 'yth'
print(len(text))         # Output: 6
print(text * 2)          # Output: 'PythonPython'
print(text + " Rocks!")  # Output: 'Python Rocks!'

Common String Methods


MethodDescription
str.lower()Converts all characters to lowercase
str.upper()Converts all characters to uppercase
str.strip()Removes whitespace or specified characters from both ends
str.replace(old, new)Replaces occurrences of a substring
str.find(sub)Finds index of first occurrence of a substring
str.split(delimiter)Splits string into list based on delimiter
str.join(list)Joins list elements into a string using a separator
str.startswith(prefix)Checks if string starts with specified prefix
str.endswith(suffix)Checks if string ends with specified suffix
str.isdigit()Returns True if string contains only digits

Usage Examples:



text = "  Python is Fun!  "

print(text.strip())                      # Removes leading/trailing spaces
print(text.lower())                      # Converts to lowercase
print(text.find("is"))                   # Output: 9
print(text.replace("Fun", "Powerful"))   # Replaces substring
print(text.split())                      # Output: ['Python', 'is', 'Fun!']
print("-".join(["A", "B", "C"]))         # Output: 'A-B-C'
print(text.startswith("Py"))            # False due to leading spaces
print("123".isdigit())                   # Output: True

Conclusion


Strings in Python are versatile and essential for text-based operations. From slicing and joining to formatting and condition checks, mastering string manipulation helps you write clean, expressive, and efficient Python code.


Written & researched by Dr. Shahin Siami

Related Articles

Complete Guide to Python Decorators – Enhancing Function Behavior with Reusable Logic

Decorators in Python are a powerful tool for modifying or extending the behavior of functions and classes without changing their original code. They allow developers to implement reusable logic such as logging, authentication, caching, or timing in a clean and maintainable way. This article explores the structure, definition, common use cases, and practical examples of decorators in Python.

Continue

Comprehensive Guide to Python Classes – Object-Oriented Design, Structure, Inheritance, and Practical Use

Classes in Python are the foundation of object-oriented programming, allowing developers to define complex data structures, encapsulate logic, and create scalable, maintainable systems. This article walks through the fundamentals of defining classes, constructors, methods, inheritance, encapsulation, and real-world applications in Python projects.

Continue

Several example codes

understand the Python programming language

Continue

Complete Guide to Getting Text Input from Users in Python

In Python, accepting input from users is one of the simplest yet most powerful features for interactive programming. This article explores the input() function in depth, explains how to cast types, validate user data, and use input within loops and conditions. Real-life examples help clarify each concept, making this guide perfect for beginners and intermediate learners.

Continue

Comprehensive Guide to Functions in Python: Structure, Types, and Use Cases

Functions in Python are essential building blocks for writing modular, reusable, and maintainable code. This article introduces function definitions, distinguishes between built-in and user-defined functions, explores parameters and return values, and presents advanced topics such as recursion and lambda expressions. Whether you're a beginner or brushing up for interviews, this guide offers a clear and accessible foundation.

Continue

Loops, Iterators, and Repetition Control in Python

Loops, Iterators, and Repetition Control in Python

Continue