(toc)


A string in Python is a sequence of characters enclosed within single quotes ('), double quotes ("), or triple quotes (''' or """). Strings are one of the most commonly used data types in Python and are essential for working with text-based data.


Creating Strings

Strings can be created using:

  • Single quotes: 'Hello'
  • Double quotes: "World"
  • Triple quotes: '''Multiline String''' or """Multiline String"""

Examples:


# Single and double-quoted strings name = 'Alice' greeting = "Hello, World!" # Triple-quoted string for multi-line text message = """This is a multi-line string.""" print(name) # Output: Alice print(greeting) # Output: Hello, World! print(message) # Output: This is a multi-line string.

String Indexing and Slicing

Strings are indexed, allowing you to access specific characters or slices of the string.

Indexing

Python uses zero-based indexing.


text = "Python" # Access individual characters print(text[0]) # Output: P print(text[-1]) # Output: n (negative indexing starts from the end)

Slicing

You can extract substrings using slicing syntax: string[start:end:step].


text = "Python Programming" # Slice examples print(text[0:6]) # Output: Python print(text[7:]) # Output: Programming print(text[:6]) # Output: Python print(text[::2]) # Output: Pto rgamn (every second character)

String Immutability

Strings in Python are immutable, meaning they cannot be modified after creation.

Example:


text = "Hello" # This will raise an error # text[0] = 'h' # TypeError: 'str' object does not support item assignment

However, you can create a new string based on the original.


text = "Hello" text = "h" + text[1:] # New string print(text) # Output: hello

String Operations

  1. Concatenation

Combine strings using the + operator.


first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name print(full_name) # Output: John Doe
  1. Repetition

Repeat a string using the * operator.


text = "Hi! " print(text * 3) # Output: Hi! Hi! Hi!
  1. Membership Testing

Check if a substring exists using the in keyword.


text = "Python Programming" print("Python" in text) # Output: True print("Java" in text) # Output: False

String Methods

Python provides several built-in methods to manipulate strings.

Method Description
lower() Converts all characters to lowercase.
upper() Converts all characters to uppercase.
strip() Removes leading and trailing whitespace.
replace(old, new) Replaces occurrences of a substring with another.
split(delimiter) Splits the string into a list based on a delimiter.
join(iterable) Joins elements of an iterable with the string as a separator.
startswith(sub) Checks if the string starts with a specific substring.
endswith(sub) Checks if the string ends with a specific substring.

Examples:


text = " Python Programming " # Convert case print(text.lower()) # Output: " python programming " print(text.upper()) # Output: " PYTHON PROGRAMMING " # Strip whitespace print(text.strip()) # Output: "Python Programming" # Replace substrings print(text.replace("Python", "Java")) # Output: " Java Programming " # Split and join words = text.strip().split() # Split into a list print(words) # Output: ['Python', 'Programming'] joined = "-".join(words) # Join with a hyphen print(joined) # Output: Python-Programming

String Formatting

Python provides several ways to format strings for dynamic content.

  1. Using f-strings (formatted string literals)

name = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.") # Output: My name is Alice and I am 25 years old.
  1. Using format()

print("My name is {} and I am {} years old.".format(name, age)) # Output: My name is Alice and I am 25 years old.
  1. Using % Operator

print("My name is %s and I am %d years old." % (name, age)) # Output: My name is Alice and I am 25 years old.

Escape Characters

Use a backslash () to include special characters in strings.

Escape Character Description
' Single quote
" Double quote
\ Backslash
n New line
t Tab

Example:


text = "He said, "Python is amazing!"nLet's learn it together." print(text)

Output:


He said, "Python is amazing!" Let's learn it together.

String Iteration

Strings can be iterated over using a for loop.

Example:


text = "Python" for char in text: print(char)

Output:


P y t h o n

Leave a Reply