Skip to content

Latest commit

 

History

History
231 lines (150 loc) · 2.48 KB

File metadata and controls

231 lines (150 loc) · 2.48 KB

Strings in Python


1. Introduction

A string is used to store text in Python.

Anything written inside single quotes ' ' or double quotes " " is considered a string.

Examples of strings:

  • Names
  • Cities
  • Messages
  • Email addresses
  • Sentences

Strings are one of the most frequently used data types in programming.


2. Creating Strings

You can create strings using single or double quotes.

name = "Arjun"
city = 'Mumbai'
message = "Welcome to Python"

Both single and double quotes work the same way.


3. Printing Strings

print("Hello World")

Printing a variable:

name = "Riya"
print(name)

4. String Indexing

Each character in a string has a position (index).

Important rule:

  • Index starts from 0

Example:

text = "Python"
print(text[0])
print(text[1])

Output:

P
y

Index positions:

P  y  t  h  o  n
0  1  2  3  4  5

Negative Indexing

Python also supports negative indexing.

  • -1 means last character
  • -2 means second last

Example:

text = "Python"
print(text[-1])

Output:

n

5. String Slicing

Slicing allows you to extract part of a string.

Syntax:

string[start:end]

Example:

text = "Programming"
print(text[0:6])

Output:

Progra

Important:

  • Start index is included
  • End index is excluded

Another example:

print(text[3:8])

Slicing Without Start or End

text = "Python"

print(text[:4])   # From start to index 4
print(text[2:])   # From index 2 to end

6. String Concatenation

Concatenation means joining strings.

Using + operator:

first = "Hello"
second = "World"
print(first + " " + second)

Output:

Hello World

7. Length of a String

Use len() to count characters.

text = "Python"
print(len(text))

Output:

6

8. Common Beginner Mistakes

  1. Trying to change a character directly
text = "Python"
text[0] = "J"   # Error

Strings are immutable (cannot be changed directly).

  1. Forgetting quotes
name = Rahul   # Error
  1. Wrong slicing index

9. Practice Exercises

  1. Create a string with your city name
  2. Print the first character
  3. Print the last character
  4. Print first 3 characters
  5. Join two strings using +
  6. Print length of a string

Example practice:

city = "Delhi"
print(city[0])
print(city[-1])
print(city[:3])
print(len(city))