Strings in Python

  • String Basics

What is a String

A string is a sequence of characters enclosed within quotes. These characters can include letters, numbers, symbols, and spaces.

name = "Pooja"
greeting = 'Hello World'
paragraph = """This is a multi-line string"""

Types of Quotes

  • Single quotes ' '
  • Double quotes " "
  • Triple quotes ''' ''' or """ """ (used for multi-line text)

Indexing

Each character in a string has a position called an index.

text = "Python"print(text[0])   # P
print(text[1])   # y
print(text[-1])  # n
  • Positive indexing starts from 0
  • Negative indexing starts from -1 (from end)

Slicing

Slicing extracts a portion of a string.

text = "Python"print(text[0:3])   # Pyt
print(text[2:])    # thon
print(text[:4])    # Pyth
print(text[::2])   # Pto

String Immutability

Strings cannot be changed after creation.

text = "Hello"
# text[0] = "h"  # Error

//To modify a string, create a new one:

text = "Hello"
new_text = "h" + text[1:]

  • String Operations

Concatenation

Combining strings using +:

a = "Hello"
b = "Python"
print(a + " " + b)

Repetition

Repeating strings using *:

print("Hi " * 3)

Membership Operators

//Check if a substring exists:

print("Py" in "Python")       # True
print("Java" not in "Python") # True

//Iterating Through Strings

for char in "Python":
    print(char)

//Length of String

print(len("Python"))  # 6

  • String Methods

Python provides many built-in methods to manipulate strings.


//Case Conversion Methods

text = "python programming"print(text.upper())      # PYTHON PROGRAMMING
print(text.lower())      # python programming
print(text.title())      # Python Programming
print(text.capitalize()) # Python programming

//Searching Methods

text = "Hello World"print(text.find("World"))   # Returns index
print(text.index("Hello"))  # Similar to find

//Checking Methods

rint("abc".isalpha())   # True
print("123".isdigit())   # True
print("abc123".isalnum())# True
print("hello".islower()) # True
print("HELLO".isupper()) # True

//Replace and Split Methods

text = "Hello World"print(text.replace("World", "Python"))
print(text.split())   # ['Hello', 'World']

//Join Method

words = ["Learn", "Python"]print(" ".join(words))  # Learn Python

//Strip Methods

text = "  Hello  "print(text.strip())   # Remove spaces
print(text.lstrip())  # Remove left spaces
print(text.rstrip())  # Remove right spaces

Difference:

  • find() returns -1 if not found
  • index() raises an error if not found


  • String Formatting

String formatting helps create dynamic and readable output.


//f-strings (Recommended)

name = "Pooja"
age = 20print(f"My name is {name} and I am {age} years old")

//format() Method

print("My name is {} and I am {}".format(name, age))

//Old Style Formatting

print("My name is %s and I am %d" % (name, age))

//Advanced Formatting

price = 99.4567print(f"{price:.2f}")   # 99.46
print(f"{price:.1f}")   # 99.5

//Aligning Text

text = "Python"print(f"{text:<10}")  # Left align
print(f"{text:^10}")  # Center align
print(f"{text:>10}")  # Right align

  • Escape Characters

Escape characters are used to represent special characters in strings.


Common Escape Characters

EscapeMeaning
\nNew line
\tTab space
\Backslash
Single quote
Double quote

Examples

("Hello\nWorld")
print("Name:\tPooja")
print("He said \"Hello\"")
print("Path: C:\\Users\\Name")

Raw Strings
Raw strings ignore escape characters:
print(r”C:\Users\Name”)


Conclusion

Strings are a fundamental part of Python programming, used in almost every application involving text. From simple operations like concatenation to advanced formatting and manipulation, Python provides powerful tools to work with strings efficiently.

By mastering string basics, operations, methods, and formatting techniques, learners can handle text data effectively and build user-friendly programs. This knowledge is essential for areas like web development, data processing, and automation.

A strong understanding of strings will help learners progress to more advanced topics such as file handling, data analysis, and real-world application development.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *