3-1-2-19. String Methods

So far, we’ve seen two distinct ways to process

data with Python, operators and functions.

We’ve used operators like these,

which process the two values on either side of the operator.

We’ve also used functions like print and len.

Functions are very similar to operators.

In fact, the only real difference is in how they look.

Function Inputs are put in parentheses rather than being placed next to an operator,

and functions have descriptive names rather than short symbols.

There is a third technique for operating on values, methods.

The best way to learn about methods is with an example.

Consider this title method.

Methods are related to functions,

but unlike functions, methods are associated with specific types of objects.

That is, there are different methods depending on the type of data you’re working with.

In this example, the object is a string with the value

Sebastian Thrun and we are calling its title method.

The method returns a string in title case,

meaning the first letter of each word is capitalized.

So methods are functions that belong to an object,

an object, for example, being a string.

Let’s try another string method, islower().

The lower method checks one of the characters in a string or lowercase.

In this case, the string object is sebastian thrun.

Is lower returns true since there are

no uppercase letters you’ve probably

noticed that when we call the is lower and title methods,

we use parentheses, but we haven’t put

anything in them like we did when calling functions.

Those inputs in the parentheses are called arguments.

Since methods or special types of functions that belong to an object,

the object is always the first argument to a method.

So, is lower and title actually did have

an argument although there was nothing in the parentheses.

The argument is disguised as the string object.

Let’s try a method that takes more arguments than just the object, count.

Here, the count method returns how many times the substring fish occurs in the string.

The object is the string, one fish,

two fish, red fish, blue fish,

and the method is dot count,

and four occurrences of the word fish exist in the string.

지금까지 처리하는 두 가지 별개의 방법을 살펴보았습니다.

Python, 연산자 및 함수로 데이터.

우리는 다음과 같은 연산자를 사용했습니다.

연산자의 양쪽에 있는 두 값을 처리합니다.

우리는 또한 print 및 len과 같은 기능을 사용했습니다.

함수는 연산자와 매우 유사합니다.

사실, 유일한 진짜 차이점은 그들이 어떻게 생겼는지에 있습니다.

함수 입력은 연산자 옆에 배치되지 않고 괄호 안에 넣습니다.

함수에는 짧은 기호가 아닌 설명적인 이름이 있습니다.

값, 메서드를 조작하는 세 번째 기술이 있습니다.

방법에 대해 배우는 가장 좋은 방법은 예제를 사용하는 것입니다.

이 제목 방법을 고려하십시오.

메소드는 함수와 관련이 있으며,

그러나 함수와 달리 메서드는 특정 유형의 개체와 연결됩니다.

즉, 작업 중인 데이터 유형에 따라 다른 방법이 있습니다.

이 예에서 객체는 값이 있는 문자열입니다.

Sebastian Thrun과 우리는 그 제목 메서드를 호출합니다.

이 메서드는 제목의 경우 문자열을 반환하고,

각 단어의 첫 글자가 대문자임을 의미합니다.

따라서 메소드는 객체에 속하는 함수입니다.

개체, 예를 들어 문자열입니다.

다른 문자열 메서드인 islower()를 사용해 보겠습니다.

lower 메서드는 문자열 또는 소문자의 문자 중 하나를 확인합니다.

이 경우 문자열 개체는 sebastian thrun입니다.

가 있기 때문에 더 낮은 수익률이 사실입니다.

당신은 아마 대문자가 없습니다

is lower 및 title 메서드를 호출할 때

괄호를 사용하지만 넣지 않았습니다.

함수를 호출할 때 했던 것처럼 그 안에 있는 모든 것.

괄호 안의 입력을 인수라고 합니다.

객체에 속하는 메소드나 특수한 형태의 함수이기 때문에,

객체는 항상 메서드에 대한 첫 번째 인수입니다.

따라서 더 낮고 제목은 실제로

괄호 안에는 아무것도 없었지만 인수.

인수는 문자열 개체로 위장합니다.

개체 count보다 더 많은 인수를 사용하는 메서드를 사용해 보겠습니다.

여기에서 count 메서드는 문자열에서 하위 문자열 fish가 몇 번 발생했는지를 반환합니다.

대상은 끈, 물고기 한 마리,

두 마리의 물고기, 붉은 물고기, 푸른 물고기,

방법은 도트 수입니다.

문자열에 fish라는 단어가 4번 나타납니다.

String Methods

In this video you were introduced to methodsMethods are like some of the functions you have already seen:

  1. len(“this”)
  2. type(12)
  3. print(“Hello world”)

These three above are functions – notice they use parentheses, and accept one or more arguments. Functions will be studied in much more detail in a later lesson!

method in Python behaves similarly to a function. Methods actually are functions that are called using dot notation. For example, lower() is a string method that can be used like this, on a string called “sample string”: sample_string.lower().

Methods are specific to the data type for a particular variable. So there are some built-in methods that are available for all strings, different methods that are available for all integers, etc.

Below is an image that shows some methods that are possible with any string.

Each of these methods accepts the string itself as the first argument of the method. However, they also could receive additional arguments, that are passed inside the parentheses. Let’s look at the output for a few examples.

>>> my_string.islower()
True
>>> my_string.count('a')
2
>>> my_string.find('a')
3

You can see that the count and find methods both take another argument. However, the .islower() method does not accept another argument.

No professional has all the methods memorized, which is why understanding how to use documentation and find answers is so important. Gaining a strong grasp of the foundations of programming will allow you to use those foundations to use documentation to build so much more than someone who tries to memorize all the built-in methods in Python.

One important string method: format()

We will be using the format() string method a good bit in our future work in Python, and you will find it very valuable in your coding, especially with your print statements.

We can best illustrate how to use format() by looking at some examples:

Example 1

print("Mohammed has {} balloons".format(27))

Example 1 Output

Mohammed has 27 balloons

Example 2

animal = "dog"
action = "bite"
print("Does your {} {}?".format(animal, action))

Example 2 Output

Does your dog bite?

Example 3

maria_string = "Maria loves {} and {}"
print(maria_string.format("math", "statistics"))

Example 3 Output

Maria loves math and statistics

Notice how in each example, the number of pairs of curly braces {} you use inside the string is the same as the number of replacements you want to make using the values inside format().

More advanced students can learn more about the formal syntax for using the format() string method here.

https://docs.python.org/3.6/library/string.html#format-string-syntax

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading