Home Tutorials Python Tutorial Strings
Strings

Strings


Definition: Strings in Python are sequences of characters used to store and manipulate text. They are created by enclosing characters in single quotes (' ') or double quotes (" ").

Why: Text processing is one of the most common programming tasks. Learning strings early allows you to handle names, addresses, messages, and any other textual data your program might need.

Syntax

text_variable = "Hello, Python!"

Example

name = "Python"
print(name)           # Output: Python
print(name[0])        # Output: P (Accesses the first character)
print(len(name))       # Output: 6 (Gets the length of the string)
print(name.lower())    # Output: python (Converts to lowercase)

String Features

  • Indexing: You can access individual characters by their position (index), starting from 0.
  • Methods: Python provides built-in tools like .upper(), .lower(), and .strip() to modify text easily.
  • Concatenation: You can combine strings using the + operator.

Example with Formatting (F-Strings)

F-strings provide a concise and convenient way to embed expressions inside string literals.

name = "Ramesh"
age = 30
print(f"My name is {name} and I am {age} years old.")

Key Notes

  • Strings are immutable, meaning once a string is created, you cannot change its individual characters.
  • You can use triple quotes (""" """) for multi-line strings.
  • Negative indexing (e.g., name[-1]) allows you to access characters from the end of the string.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Strings to test your knowledge.

Exercise »