Python 4th Module Strings
Python 4th Module Strings
• String Slicing:
•Use slicing to access a range of characters by specifying a start index and an end index (the end
index is not included).
•Syntax: string[start:end]
Example:
Indexing Rules:
•Index Out of Range: Accessing an index beyond the string length raises an IndexError.
•Invalid Index Type: Using non-integer indices (like floats) will raise a TypeError.
Negative Indexing:
•Python allows negative indexing for strings.
•-1 refers to the last character, -2 to the second last, and so on.
•Example:
Error Message:
TypeError: 'str' object does not support item assignment
Reassigning Strings:
•Instead of modifying, you can reassign the variable to a new string.
•Example:
Deleting a String:
•While you cannot delete individual characters, you can delete the entire string variable using the del
keyword.
•Example:
Error Message:
NameError: name 'txt' is not defined
Using del Keyword:
•The del keyword can delete any object in Python, such as variables, lists, or parts of lists.
1.3. Escape Characters in Python
Purpose of Escape Characters:
•Escape characters allow inserting special or illegal characters within strings. These characters have
specific meanings in Python, like quotes within quotes.
Using the Backslash \ as an Escape Character:
•The escape character in Python is a backslash \, followed by the character you want to insert.
Example of an Illegal Character:
•A double quote within a double-quoted string will cause an error
Why it works: Triple quotes prevent Python from confusing the inner single (') and double quotes ("),
so no escape character is needed.
2. Escaping Single Quote (\')
When using single quotes around a string, any additional single quote in the text (like in “I’m”) will end the
string if it’s not escaped.
Example:
Why it works: The \' escape sequence lets Python know that the single quote in “I’m” is part of the
text, not the end of the string.
1.4. String Special Operators:
Assume string variable a holds ‘hello’ and variable b holds ‘python’ then:
Raw String:
If you write a path like "C:\Users\Asna", Python sees
\U as a special character, which can cause errors.
But if you use a raw string like r"C:\Users\Asna",
Python treats \ as normal text, so the path stays
exactly as you typed it.
Example:
1.5. String Formatting Operator:
In Python, the formatting operator % is used to insert values into strings. It works like a placeholder
system, where % is followed by a specific letter to represent different types of values, such as strings,
integers, or floating-point numbers.
Basic Syntax:
•The type is a letter that tells Python the type of value (e.g., %s for strings, %d for integers).
•Value is what you want to insert into the placeholder.
2. Integer Insertion
3. Floating-Point Insertion
4. Combining Placeholders