Strings Introduction

Python tutorial · PySpark.in

String in Python

A string is a sequence of characters enclosed within single quotes (' ') or double quotes (" ").Strings can contain letters, digits, symbols, or spaces and are widely used for storing and processing text.

Example:

PYTHON
1# Define strings
2name = "Rohan"
3greeting = 'Hello, World!'
4# Print the strings
5print(name)
6print(greeting)
▶ Output will appear here.

Key Characteristics of Strings

Strings are Immutable

Immutable – You cannot change a string after it is created.

PLAINTEXT
1text = "Hello"
2# text[0] = 'h' # This will give an error
▶ Output will appear here.

Ordered – Each character has a position called an index, starting from 0.

PYTHON
1word = "Python"
2print(word[0]) # Output: P
3print(word[5]) # Output: n
▶ Output will appear here.

Iterable – You can loop through each character in a string.

PYTHON
1for ch in "Python":
2 print(ch)
▶ Output will appear here.

Creating Strings

Single-line strings: Strings defined in one line using single or double quotes.

PLAINTEXT
1str1 = "Hello"
2str2 = 'Python'
▶ Output will appear here.

Multi-line strings (using triple quotes):Strings written across multiple lines using triple quotes (``` or """)

PLAINTEXT
1str3 = """This is
2a multi-line
3string."""
▶ Output will appear here.

Basic String Operations

  1. Concatenation (joining strings):Joining two or more strings using the + operator.
PYTHON
1str1 = "Hello"
2str2 = "World"
3result = str1 + " " + str2
4print(result) # Output: Hello World
▶ Output will appear here.

Repetition : Repeating a string multiple times using the * operator.

PYTHON
1print("Ha" * 3) # Output: HaHaHa
▶ Output will appear here.

Length of a string

The len() function returns the total number of characters in a string.

PYTHON
1name = "Megha"
2print(len(name)) # Output: 5
▶ Output will appear here.

Common String Methods

PYTHON
1text = " python programming "
2print(text.upper()) # " PYTHON PROGRAMMING "
3print(text.lower()) # " python programming "
4print(text.strip()) # "python programming" (removes spaces)
5print(text.replace("python", "java")) # " java programming "
6print(text.split()) # ['python', 'programming']
7print(text.startswith(" py")) # True
8print(text.endswith("ing ")) # True
▶ Output will appear here.

Why Strings are Important

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges