Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Built-In Data Types
  5. String in Python

String in Python

A string in Python is a sequence of characters enclosed within single quotes (‘), double quotes (“), or triple quotes (”’ ”’ or “”” “””).

Thank you for reading this post, don't forget to subscribe!
  • Strings are used to represent textual data such as names, messages, or any combination of characters.
  • A string is an ordered collection of characters used to store and manipulate text-based data in Python.
  • Indexing allows accessing individual characters from a string using their position (starting from 0).
  • Slicing allows extracting a portion (substring) of the string using a range of indices.

Examples:

text = "Hello"

# Indexing
print(text[1])      # Output: 'e'

# Slicing
print(text[1:4])    # Output: 'ell'

Python provides powerful tools to insert variables and values into strings.

1.) Using format() method:

name = "Alice"
print("My name is {}".format(name))  # Output: My name is Alice

2.) Using f-strings (Python 3.6+):

name = "Bob"
print(f"My name is {name}")          # Output: My name is Bob

Escape sequences are used to represent special characters within strings that cannot be typed directly.

image 2

Example:

print("Hello\nWorld")   # Output:
# Hello
# World

print("Name:\tJohn")    # Output: Name:	John

How can we help?