💥 WordPress https://computerclassinsrilanka.wordpress.com
💥 Facebook https://web.facebook.com/itclasssrilanka
Points on Python Strings
-
Definition of Strings
- Strings in Python are surrounded by either single (
') or double (") quotation marks.
Example:print("Hello") print('Hello')
- Strings in Python are surrounded by either single (
-
Quotes Inside Strings
- Quotes inside strings can be used as long as they don't match the outer quotes.
Example:print("It's alright") print("He is called 'Johnny'") print('He is called "Johnny"')
- Quotes inside strings can be used as long as they don't match the outer quotes.
-
Assigning Strings to Variables
- Strings can be assigned to variables using the equal sign (
=).
Example:a = "Hello" print(a)
- Strings can be assigned to variables using the equal sign (
-
Multiline Strings
- Multiline strings are created using triple quotes (
"""or''').
Example:
Or:a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.""" print(a)a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit.''' print(a)
- Multiline strings are created using triple quotes (
-
Strings as Arrays
- Strings are arrays of bytes representing Unicode characters.
- Access elements using square brackets (
[]).
Example:a = "Hello, World!" print(a[1]) # Outputs 'e'
-
Looping Through a String
- Strings can be iterated using a
forloop.
Example:for x in "banana": print(x)
- Strings can be iterated using a
-
String Length
- Use the
len()function to get the length of a string.
Example:a = "Hello, World!" print(len(a)) # Outputs 13
- Use the
-
Check String Presence
- Use the
inkeyword to check if a substring is present.
Example:txt = "The best things in life are free!" print("free" in txt) # Outputs True - Use
inwith anifstatement:if "free" in txt: print("Yes, 'free' is present.")
- Use the
-
Check String Absence
- Use the
not inkeyword to check if a substring is not present.
Example:txt = "The best things in life are free!" print("expensive" not in txt) # Outputs True - Use
not inwith anifstatement:if "expensive" not in txt: print("No, 'expensive' is NOT present.")
- Use the
-
Exercise
- Question:
x = 'Welcome' print(x[3]) - Answer: The output will be:
c(since indexing starts at 0).
Slicing Syntax
- Strings can be sliced using the syntax
[start:end]. - The slicing returns characters from the
startindex up to, but not including, theendindex.
Example:b = "Hello, World!" print(b[2:5]) # Outputs 'llo' - Note: Indexing starts at 0.
- Strings can be sliced using the syntax
-
Slice From the Start
- Omitting the
startindex makes the slice begin from the start of the string.
Example:b = "Hello, World!" print(b[:5]) # Outputs 'Hello'
- Omitting the
-
Slice To the End
- Omitting the
endindex makes the slice go until the end of the string.
Example:b = "Hello, World!" print(b[2:]) # Outputs 'llo, World!'
- Omitting the
-
Negative Indexing
- Negative indices count from the end of the string.
- Example:
b = "Hello, World!" print(b[-5:-2]) # Outputs 'orl'- Here,
-5corresponds to "o" in "World!" and-2excludes "d" in "World!".
- Here,
-
Exercise
- Question:
x = 'Welcome' print(x[3:5]) - Answer: The output will be:
co(characters from index 3 to 4, as index 5 is not included).
Points on Python - Modify Strings
-
Built-in Methods
- Python provides built-in methods to modify strings.
-
Convert to Upper Case
- The
upper()method converts all characters in the string to upper case.
Example:a = "Hello, World!" print(a.upper()) # Outputs: "HELLO, WORLD!"
- The
-
Convert to Lower Case
- The
lower()method converts all characters in the string to lower case.
Example:a = "Hello, World!" print(a.lower()) # Outputs: "hello, world!"
- The
-
Remove Whitespace
- The
strip()method removes whitespace from the beginning and the end of the string.
Example:a = " Hello, World! " print(a.strip()) # Outputs: "Hello, World!"
- The
-
Replace Substring
- The
replace()method replaces a specified substring with another substring.
Example:a = "Hello, World!" print(a.replace("H", "J")) # Outputs: "Jello, World!"
- The
-
Split String
- The
split()method splits the string into substrings based on a specified separator and returns them as a list.
Example:a = "Hello, World!" print(a.split(",")) # Outputs: ['Hello', ' World!']
- The
-
String Methods Reference
- Python provides many more string methods. Refer to Python's String Methods Reference for a complete list.
-
Exercise
- Question:
What is the correct syntax to print a string in upper case letters?'Welcome'.upper()✅'Welcome'.toUpper()❌'Welcome'.toUpperCase()❌
- Correct Answer:
'Welcome'.upper()
String Concatenation
-
String Concatenation
- Concatenation is the process of combining two or more strings.
-
Using the
+Operator- The
+operator can be used to concatenate strings.
Example:a = "Hello" b = "World" c = a + b print(c) # Outputs: "HelloWorld"
- The
-
Adding a Space Between Strings
- To include a space between concatenated strings, add
" "in between.
Example:a = "Hello" b = "World" c = a + " " + b print(c) # Outputs: "Hello World"
- To include a space between concatenated strings, add
-
Exercise
- Question:
What is the correct syntax to merge variablexandyinto variablez?z = x, y❌z = x = y❌z = x + y✅
- Correct Answer:
z = x + y
Format Strings
-
String Format Problem
- Strings and numbers cannot be combined directly using
+.
Example:age = 36 txt = "My name is John, I am " + age # ❌ Results in an error print(txt)
- Strings and numbers cannot be combined directly using
-
Solutions for Combining Strings and Numbers
- Use f-strings or the
format()method.
- Use f-strings or the
-
F-Strings
- Introduced in Python 3.6 and is the preferred method for string formatting.
- Add an
fbefore the string and use{}as placeholders.
Example:age = 36 txt = f"My name is John, I am {age}" print(txt) # Outputs: "My name is John, I am 36"
-
Placeholders and Modifiers
- Placeholders in f-strings can include variables, operations, and modifiers.
-
Placeholders for Variables
- Example:
price = 59 txt = f"The price is {price} dollars" print(txt) # Outputs: "The price is 59 dollars"
- Example:
-
Using Modifiers in Placeholders
- A modifier formats the value inside a placeholder.
- Example with
.2f(fixed-point number with 2 decimals):price = 59 txt = f"The price is {price:.2f} dollars" print(txt) # Outputs: "The price is 59.00 dollars"
-
Performing Math Operations in Placeholders
- Example:
txt = f"The price is {20 * 59} dollars" print(txt) # Outputs: "The price is 1180 dollars"
- Example:
-
Exercise
- Question: If
x = 9, what is the correct syntax to print"The price is 9.00 dollars"?print(f'The price is {x:.2f} dollars')✅print(f'The price is {x:2} dollars')❌print(f'The price is {x:format(2)} dollars')❌
- Correct Answer:
print(f'The price is {x:.2f} dollars') # Outputs: "The price is 9.00 dollars"
Escape Characters in Python
-
Purpose of Escape Characters
- Escape characters allow the insertion of characters that are illegal or problematic in a string.
- They are written as a backslash
\followed by the character to insert.
-
Example of Illegal Character
- Using double quotes inside a string surrounded by double quotes results in an error:
txt = "We are the so-called "Vikings" from the north." # ❌ Error
- Using double quotes inside a string surrounded by double quotes results in an error:
-
Fixing the Problem with Escape Characters
- Use
\"to include double quotes in a string:txt = "We are the so-called \"Vikings\" from the north." print(txt) # Outputs: We are the so-called "Vikings" from the north.
- Use
-
List of Escape Characters
-
\': Inserts a single quote.
Example:txt = 'It\'s a sunny day.' print(txt) # Outputs: It's a sunny day. -
\\: Inserts a backslash.
Example:txt = "This is a backslash: \\" print(txt) # Outputs: This is a backslash: \ -
\n: Inserts a new line.
Example:txt = "Hello\nWorld!" print(txt) # Outputs: # Hello # World! -
\r: Inserts a carriage return.
Example:txt = "Hello\rWorld" print(txt) # Outputs: World (carriage return overwrites the line) -
\t: Inserts a tab.
Example:txt = "Hello\tWorld" print(txt) # Outputs: Hello World -
\b: Inserts a backspace.
Example:txt = "Hello\bWorld" print(txt) # Outputs: HellWorld (removes 'o') -
\f: Inserts a form feed.
Example:txt = "Hello\fWorld" print(txt) # Outputs: HelloWorld (new page indicator) -
\ooo: Inserts a character based on its octal value.
Example:txt = "\110\145\154\154\157" # Octal for 'Hello' print(txt) # Outputs: Hello -
\xhh: Inserts a character based on its hex value.
Example:txt = "\x48\x65\x6C\x6C\x6F" # Hex for 'Hello' print(txt) # Outputs: Hello
String Methods
-
General Note
- All string methods return new values and do not change the original string.
-
String Methods and Their Descriptions
| Method | Description |
|---|---|
capitalize() |
Converts the first character to upper case. |
casefold() |
Converts string into lower case (more aggressive than lower()). |
center() |
Returns a centered string. |
count() |
Returns the number of times a specified value occurs in a string. |
encode() |
Returns an encoded version of the string. |
endswith() |
Returns True if the string ends with the specified value. |
expandtabs() |
Sets the tab size of the string. |
find() |
Searches for a specified value and returns the position where it was found. |
format() |
Formats specified values in a string. |
format_map() |
Formats specified values in a string using a dictionary. |
index() |
Searches for a specified value and returns its position (raises an error if not found). |
isalnum() |
Returns True if all characters in the string are alphanumeric. |
isalpha() |
Returns True if all characters in the string are alphabetic. |
isascii() |
Returns True if all characters in the string are ASCII characters. |
isdecimal() |
Returns True if all characters in the string are decimals. |
isdigit() |
Returns True if all characters in the string are digits. |
isidentifier() |
Returns True if the string is a valid identifier. |
islower() |
Returns True if all characters in the string are lower case. |
isnumeric() |
Returns True if all characters in the string are numeric. |
isprintable() |
Returns True if all characters in the string are printable. |
isspace() |
Returns True if all characters in the string are whitespaces. |
istitle() |
Returns True if the string follows title case rules. |
isupper() |
Returns True if all characters in the string are upper case. |
join() |
Joins the elements of an iterable to the string. |
ljust() |
Returns a left-justified version of the string. |
lower() |
Converts a string to lower case. |
lstrip() |
Returns a left-trimmed version of the string. |
maketrans() |
Returns a translation table for use in string translation. |
partition() |
Splits the string into three parts: before, the separator, and after. |
replace() |
Replaces a specified value with another value in the string. |
rfind() |
Searches for a specified value and returns the last position of where it was found. |
rindex() |
Searches for a specified value and returns its last position (raises an error if not found). |
rjust() |
Returns a right-justified version of the string. |
rpartition() |
Splits the string into three parts from the right: before, the separator, and after. |
rsplit() |
Splits the string at the specified separator from the right and returns a list. |
rstrip() |
Returns a right-trimmed version of the string. |
split() |
Splits the string at the specified separator and returns a list. |
splitlines() |
Splits the string at line breaks and returns a list. |
startswith() |
Returns True if the string starts with the specified value. |
strip() |
Returns a trimmed version of the string (removes spaces from both ends). |
swapcase() |
Swaps case: lower case becomes upper case, and vice versa. |
title() |
Converts the first character of each word to upper case. |
translate() |
Returns a translated string using a translation table. |
upper() |
Converts a string to upper case. |
zfill() |
Pads the string with zeros on the left until it reaches the specified length. |

No comments:
Post a Comment