
Table of Contents(目次)
String methods
What is a method?
In this lecture, we will learn about string methods.
A method is a “function provided for data” that is used to perform some kind of processing on that data. For example, if we have data called “towel,” we can perform actions (function processing) such as ‘wash’ and 'fold.' Additionally, there may be functions available to record or retrieve information related to the data (e.g., incrementing the usage count or retrieving the current usage count).
towel.wash() # Execute the ‘wash’ action (function)
towel.fold() # Execute the ‘fold’ action (function)
towel.increment_usage() # ‘Increment the number of uses by 1’
towel.get_usage_count() # ‘Get the current number of uses’
Functions such as wash()
, fold()
, increment_usage()
, and get_usage_count()
, which are used with data, are called methods.
In this lecture, we will learn about String type methods.
Difference between methods and functions
The difference between methods and functions is as follows. In Python, you don't need to know the details of this difference, so just a quick review is sufficient.
Term | Target | Syntax | Example |
---|---|---|---|
Function | A standalone function | function() | print() |
Method | A function associated with data | var.method() 'string'.method() | text.upper() "I'm Nico, 10.".upper() |
text.upper()
The first method is upper(). This converts the letters in a string to uppercase. Let's try running the following code.
text = "I'm Nico, 10."
new_text = text.upper()
print(new_text)
The result is I'M NICO, 10.
. All letters are converted to uppercase. Other numbers and symbols remain unchanged.
Methods are used to perform operations on data. The upper() method is a function provided for String type, so it can be used on any String-type data, regardless of the text content.
When you use the upper() method, it returns a string with all characters converted to uppercase. This is assigned to the new_text variable and printed using print.
text.lower()
lower() converts the letters in a string to lowercase.
text = "I'm Nico, 10."
new_text = text.lower()
print(new_text)
The result is i'm nico, 10.
. All letters are lowercase. Other numbers and symbols remain unchanged.
text.title()
title() converts the first letter of each word in a string to uppercase and the rest to lowercase. It is used to format text as a title.
text = "i'm nico, 10."
new_text = text.title()
print(new_text)
The result is I'M Nico, 10.
. In addition to the first character and the first character immediately after a space, characters immediately after symbols such as single quotation marks are also converted to uppercase.
text.capitalize()
capitalize() converts only the first character of a string to uppercase and converts the rest to lowercase. It is used to correct the first part of a sentence to the correct format.
text = "i'm Nico, 10."
new_text = text.capitalize()
print(new_text)
The result is I'm nico, 10.
. Since all words except the first one are lowercase, you'll need to adjust again if there are proper nouns in the middle. In this case, ‘Nico’ becomes “nico.”
Methods such as title() and capitalize() are useful functions when used appropriately, but they do not always behave as intended by the programmer. For example, title() capitalizes the first letter after a single quotation mark, and capitalize() capitalizes the first letter of proper nouns.
Therefore, programmers must write code with care, adjusting the syntax as needed. For example, if you want to ensure that only the first character of a string is capitalized, regardless of the string's content, you can achieve this by writing the code as follows:
text = "i'm Nico, 10."
new_text = text[0].upper() + text[1:]
print(new_text) # I'm Nico, 10.
The above code is an application of string slicing, where the first character ([0]) is converted to uppercase using upper(), and the remaining characters ([1:]) are concatenated using the +
operator. This ensures that the first character is converted to uppercase while leaving the rest unchanged.
While Python provides convenient functions and methods, they do not always behave exactly as programmers expect. Therefore, it is essential to verify the specifications in the official documentation, test the program's behavior, and if the expected behavior is not achieved, consider alternative solutions and rewrite the code to ensure it functions properly.
text.strip()/ text.lstrip()/ text.rstrip()
strip() removes spaces and newlines from the beginning and end of a string assigned to a variable. It is used to clean up strings read from user input or files.
lstrip() removes spaces and newlines from the beginning (left side) of a string assigned to a variable. (The method name starts with “l” for “left.”)
rstrip() removes spaces and newlines from the end (right side) of a string assigned to a variable. (The method name starts with “r” for “right.”)
text = " I'm Nico, 10. "
new_text_strip = text.strip()
new_text_lstrip = text.lstrip()
new_text_rstrip = text.rstrip()
print(new_text_strip + ':(strip)') # "I'm Nico, 10."
print(new_text_lstrip + ':(lstrip)') # "I'm Nico, 10. "
print(new_text_rstrip + ':(rstrip)') # " I'm Nico, 10."

The results of strip(), lstrip(), and rstrip() are shown in the figure above. Spaces and line breaks before and after the string are removed, but spaces in the middle remain unchanged.
text.replace("old", "new")
Basics of text.replace()
replace(“old”, “new”) is used to correct or convert characters or words. It replaces all occurrences of the substring “old” in the string with “new”. “old” and ‘new’ are specified in parentheses separated by commas. Note that the substring “old” is case-sensitive.
text = 'Can you can a can as a canner can can a can?'
new_text = text.replace('can', 'X')
print(new_text) # Can you X a X as a Xner X X a X?
The result is: Can you X a X as a Xner X X a X?
All instances of “can” are replaced with “X.”
Note that the “Can” at the beginning of the string was not matched because “C” is uppercase. To match the “Can” at the beginning as well, you can use the lower() function to make the search case-insensitive.
Number of replacements for text.replace()
The replace() method can also specify the number of replacements. Specify it in the syntax text.replace(‘old’, ‘new’, count)
.
text = 'Can you can a can as a canner can can a can?'
text_lower = text.lower()
new_text = text_lower.replace('can', 'X', 2)
print(new_text) # X you X a can as a canner can can a can?
The above code converts everything to lowercase using the lower() method before using the replace() method. Therefore, the leading “Can” is also replaced in this case. The number of replacements is specified at the end of the parentheses in the repalce() method in the third line.
The execution result is X you X a can as a canner can can a can?
The parts that match “can” are replaced in two places from the beginning.
text.startswith("prefix")/ text.endswith("suffix")
startswith(“prefix”) is used to check whether a string starts with the substring “prefix.” If the string starts with the substring “prefix,” it returns True; otherwise, it returns False.
endswith(“suffix”) is used to check whether a string ends with the substring “suffix.” If the string ends with the substring “suffix,” it returns True; otherwise, it returns False.
True and False are data types called bool.
For example, to check whether the value of the variable “num” is greater than 10, use the condition num > 10
. If num is greater than 10, it returns True, and if it is less than or equal to 10, it returns False. Depending on the result of this true/false check, you can execute different processes.
For more details, see the dedicated lecture.
# startswith
text = "I'm Nico, 10."
result1 = text.startswith("I'm")
print(result1) # True
result2 = text.startswith("I am")
print(result2) # False
# endswith
text = "I'm Nico, 10."
result1 = text.endswith("!")
print(result1) # False
result2 = text.endswith("10.")
print(result2) # True
The results of the above code are as follows:
- The startswith in line 3 returns True because the text starts with “I'm.”
- Line 5 returns False because the text does not start with “I am.”
- The endswith function on line 10 returns False because the text does not end with “!”.
- The 12th line returns True because the text ends with “10.”.
Note that startswith and endswith are case-sensitive.
text.find("substring")/ text.rfind("substring")
find(“substring”) is used when you want to find where a specific word or character is located. It returns the first occurrence (index) of a substring within a string. If the substring is not found, it returns “-1.”
rfind(“substring”) searches for the substring from the right (end) and returns the first occurrence (index). (The index number of the first character in the matched substring is returned.) If the substring is not found, it returns “-1”. This is used when you want to find the last occurrence of a substring that may appear multiple times.
Note that both find and rfind are case-sensitive.
text = 'Can you can a can...'
index1 = text.find('can')
print(index1) # 8
index2 = text.rfind('can')
print(index2) # 14
find() searches from the beginning of the string and finds “can” at [8][9][10], returning the index [8] of the smallest number within that substring as the result. (The first “Can” does not match because it contains uppercase letters.)
rfind() searches from the end of the string and finds “can” at [14][15][16], returning the index [14] of the smallest number within that substring as the result.
[0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | [10] | [11] | [12] | [13] | [14] | [15] | [16] | [17] | [18] | [19] |
C | a | n | | y | o | u | | c | a | n | | a | | c | a | n | . | . | . |
text.count("substring")
count(“substring”) counts how many times a substring appears in a string and returns the number. It is used to find the number of occurrences of a specific word or character.
text = 'Can you can a can as a canner can can a can?'
text_lower = text.lower()
result = text_lower.count('can')
print(result) # 7
The above code converts everything to lowercase using the lower() method, so including the leading “Can,” the result is 7 instances of “can.”