String Operations

Python tutorial · PySpark.in

String Operations in Python

Python provides many powerful operations to work with strings.
Here are the most important string operations every beginner should learn.

1. String Concatenation (Joining Strings)

Concatenation means joining two or more strings using the + operator.

Example

PYTHON
1first_name = "Rahul"
2last_name = "Sharma"
3full_name = first_name + " " + last_name
4print(full_name) # Rahul Sharma
▶ Output will appear here.

2. String Repetition

You can repeat a string multiple times using the * operator.

Example

PYTHON
1word = "Hi! "
2print(word * 3) # Hi! Hi! Hi!
▶ Output will appear here.

3. String Comparison

Strings can be compared using operators:

Python compares strings lexicographically (dictionary/Unicode order).

Example

PYTHON
1a = "apple"
2b = "banana"
3print(a == b) # False
4print(a != b) # True
5print(a < b) # True ('a' comes before 'b')
6print(a > b) # False
▶ Output will appear here.

Case Sensitivity

String comparison is case-sensitive.

PYTHON
1print("Apple" == "apple") # False
2print("Apple" < "apple") # True ('A' < 'a' in Unicode)
▶ Output will appear here.

4. Escape Sequences in Python

Escape sequences are special characters beginning with \ that allow you to insert:

They help format and control how text is displayed.

Common Escape Sequences

Escape

Meaning

Example

Output

\'

Single quote

'It\'s Python'

It's Python

\"

Double quote

"He said, \"Hello\""

He said, "Hello"

\\

Backslash

"C:\\Users\\Megha"

C:\Users\Megha

\n

New line

"Hello\nWorld"

Hello
World

\t

Tab space

"Hello\tWorld"

Hello World

\r

Carriage return

"Hello\rWorld"

World

\b

Backspace

"Hello\bWorld"

HellWorld

\f

Form feed

Rarely used

Prints on next page

\ooo

Octal value

"\110\145\154\154\157"

Hello

\xhh

Hex value

"\x48\x65\x6c\x6c\x6f"

Hello

\uXXXX

Unicode (16-bit)

"\u2764"


\UXXXXXXXX

Unicode (32-bit)

"\U0001F600"

😀

Examples

PYTHON
1print("Hello\nPython") # New line
2print("Name:\tRohan") # Tab space
3print("She said, \"Hi!\"") # Quotes inside string
4print("C:\\Users\\Rohan") # File path
▶ Output will appear here.

5. Raw Strings

Raw strings ignore escape sequences.
Prefix the string with r or R.

Example

PYTHON
1path = r"C:\Users\Rohan"
2print(path) # C:\Users\Rohan
▶ Output will appear here.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges