Dictionary

Home / Python / Dictionary

Dictionary


1. What is a String?

string is a sequence of characters (letters, numbers, symbols, etc.) enclosed in single, double, or triple quotes.

single_quote_str = 'Hello'
double_quote_str = "World"
multi_line_str = '''This is a
multi-line string'''

Strings in Python are immutable, meaning once a string is created, it cannot be modified, though you can create new strings from operations.


2. String Representations

Single and Double Quotes: Both single (') and double (") quotes can be used to define strings, and Python treats them the same.

name = 'Alice'
surname = "Smith"

Escape Characters: Certain characters are preceded by a backslash (\) to represent special characters:

newline = "Hello\nWorld"  # \n creates a new line
tab = "Hello\tWorld"      # \t adds a tab space


Raw Strings: Raw strings treat backslashes (\) as literal characters, often used in regular expressions or file paths.

raw_str = r"C:\new_folder\file.txt"

Triple Quotes: Triple quotes (''' or """) are used for multi-line strings.
multi_line = """This is a
multi-line string"""


3. String Functions and Methods

Python provides a variety of built-in functions and methods for working with strings.
Common String Functions:

 len(): Returns the length of a string.
s = "Hello"
print(len(s))
Output: 5

Common String Methods:
.upper(): Converts all characters in the string to uppercase.

 s = "hello"
 print(s.upper()) 
Output: "HELLO

.lower(): Converts all characters in the string to lowercase.

s = "HELLO"
print(s.lower()) 
Output: "hello"

.strip(): Removes leading and trailing whitespace (or specified characters).

s = "  Hello  "
print(s.strip()) 
Output: "Hello"

.replace(): Replaces a substring with another substring.

s = "Hello World"
print(s.replace("World", "Python")) 
Output: "Hello Python"

.split(): Splits the string into a list based on a delimiter (default is whitespace).

s = "apple,banana,grape"
print(s.split(",")) 
Output: ['apple', 'banana', 'grape']

.join(): Joins a sequence of strings using a specified separator.

list_of_fruits = ["apple", "banana", "grape"]
print(", ".join(list_of_fruits)) 
Output: "apple, banana, grape"

.startswith() and .endswith(): Check if a string starts or ends with a particular substring.

s = "Hello World"
print(s.startswith("Hello")) 
Output: True

print(s.endswith("Python"))  
Output: False


4. String Indexing and Slicing

Indexing: Strings are indexed, allowing access to specific characters. Indexing starts from 0 (zero-based).

s = "Python"
print(s[0]) 
Output: "P"

print(s[-1]) 
Output: "n" (negative indexing starts from the end)

Slicing: You can extract a substring using slicing. The syntax is [start:stop:step].

s = "Python"
print(s[0:2]) 
Output: "Py" (characters from index 0 to 1)

print(s[1:4]) 
Output: "yth" (characters from index 1 to 3)

print(s[::2]) 
Output: "Pto" (every second character)
 
 
5. String Formatting

a) Concatenation: Using + operator to join strings.

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) 
Output: "John Doe"

b) Using format() Method:
  • Placeholder {} is used within the string, and the format() method replaces it with the passed values.
age = 25
name = "Alice"
print("My name is {} and I am {} years old.".format(name, age))

c) Formatted String Literals (f-strings):
  • Python 3.6 introduced f-strings, which allow embedding expressions inside string literals, prefixed with an f.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

d) Percent Formatting (%):
  • Another older method for formatting strings is by using % followed by format specifiers.
name = "John"
age = 30
print("My name is %s and I am %d years old." % (name, age))