Strings in Python

In Python, strings are sequences of characters enclosed in either single quotes (`'`) or double quotes (`"`). They are immutable, meaning once a string is created, it cannot be changed. However, you can create new strings based on operations performed on the original string.

### Basic String Operations

1. **Creating Strings:**
   ```python
   single_quoted = 'Hello, World!'
   double_quoted = "Hello, World!"
   ```

2. **Multiline Strings:**
   You can create multiline strings using triple quotes (`'''` or `"""`).
   ```python
   multiline_string = """This is a
   multiline string."""
   ```

3. **String Concatenation:**
   You can concatenate strings using the `+` operator.
   ```python
   greeting = "Hello"
   name = "Alice"
   message = greeting + ", " + name + "!"
   print(message)  # Output: Hello, Alice!
   ```

4. **String Repetition:**
   You can repeat a string using the `*` operator.
   ```python
   laugh = "ha"
   print(laugh * 3)  # Output: hahaha
   ```

5. **String Indexing:**
   You can access individual characters in a string using indexing.
   ```python
   s = "Python"
   print(s[0])  # Output: P
   print(s[-1]) # Output: n (negative index counts from the end)
   ```

6. **String Slicing:**
   You can get a substring using slicing.
   ```python
   s = "Python"
   print(s[1:4])  # Output: yth (from index 1 to 3)
   print(s[:4])   # Output: Pyth (from start to index 3)
   print(s[2:])   # Output: thon (from index 2 to end)
   ```

7. **String Length:**
   Use the `len()` function to get the length of a string.
   ```python
   s = "Python"
   print(len(s))  # Output: 6
   ```

8. **String Methods:**
   Python provides many built-in methods to manipulate strings.
   - `str.lower()`: Converts the string to lowercase.
   - `str.upper()`: Converts the string to uppercase.
   - `str.strip()`: Removes leading and trailing whitespace.
   - `str.replace(old, new)`: Replaces occurrences of `old` with `new`.
   - `str.split(delimiter)`: Splits the string into a list based on the delimiter.
   - `str.join(iterable)`: Joins elements of an iterable into a single string.

   Example:
   ```python
   s = "  Hello, World!  "
   print(s.strip())           # Output: Hello, World!
   print(s.lower())           # Output:   hello, world!  
   print(s.replace("World", "Python"))  # Output:   Hello, Python!  
   print(s.split(","))        # Output: ['  Hello', ' World!  ']
   print("-".join(["2023", "10", "05"]))  # Output: 2023-10-05
   ```

9. **String Formatting:**
   - **f-strings (Python 3.6+):**
     ```python
     name = "Alice"
     age = 30
     print(f"My name is {name} and I am {age} years old.")
     ```
   - **`str.format()`:**
     ```python
     print("My name is {} and I am {} years old.".format(name, age))
     ```
   - **% formatting (older style):**
     ```python
     print("My name is %s and I am %d years old." % (name, age))
     ```

10. **Escape Characters:**
    - `\n`: Newline
    - `\t`: Tab
    - `\\`: Backslash
    - `\'` or `\"`: Single or double quote

    Example:
    ```python
    print("Hello\nWorld")  # Output: Hello
                           #         World
    ```

11. **Checking Substrings:**
    - `in` keyword: Checks if a substring exists in a string.
    ```python
    s = "Hello, World!"
    print("World" in s)  # Output: True
    ```

12. **String Immutability:**
    Strings cannot be changed in place. For example:
    ```python
    s = "hello"
    s[0] = "H"  # This will raise a TypeError
    ```
    Instead, you can create a new string:
    ```python
    s = "H" + s[1:]
    print(s)  # Output: Hello
    ```
Unicode and Encoding
Python strings are Unicode by default. You can encode them into bytes using specific encodings like UTF-8:
```python
s = "Hello, World!"
encoded = s.encode("utf-8")
print(encoded)  # Output: b'Hello, World!'
```

And decode bytes back into strings:
```python
decoded = encoded.decode("utf-8")
print(decoded)  # Output: Hello, World!
```

Raw Strings
Raw strings treat backslashes as literal characters and are useful for regex or file paths:
```python
path = r"C:\Users\Name\Documents"
print(path)  # Output: C:\Users\Name\Documents
```

These are the basics of working with strings in Python. Let me know if you'd like to dive deeper into any specific topic!

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos