Often programming involves more than numbers and arithmetic.
There may be situations where you need to work with text.
To work with text in Python,
you will need to use a string,
which is an immutable ordered series of characters.
More on the immutable ordered part later.
You can create a string by using quotes.
Single or double quotes work equally well,
although there are some edge cases, which we will work through.
In each of these cases I printed the string “hello” and got the output “hello”.
We can set a variable to be a string the same way we did with numbers.
Strings can include any characters,
even spaces, punctuation and numbers.
However, what do we do when we want quotation marks in our string?
Since we use quotation marks to define our strings,
this presents a small problem.
Here the code doesn’t work the way we want it to.
Python offers two solutions to this problem.
The first is to place the string in single quotes rather than double quotes, like this.
You can use either type of quote to define strings,
but sometimes you’ll need to define a string that includes both single and double quotes.
What then? In that case,
you can use the backslash to escape quotes.
Here the string is delimited by single quotes.
The single quote within the string is preceded by a backslash so that Python
knows that it should be interpreted as part of
the string rather than the quote that ends the string.
Once our strings are defined,
there are a few operations that are used for
integers and floats that we can also use for strings.
For example, we can use the plus sign to put strings together,
and we can use multiplication to repeat strings.
Let’s look at an example of each.
Here our variables are holding two words.
We can use the plus sign to concatenate the two strings together and print the result.
This is fundamentally different from numeric addition.
However, notice the two names have been squished together.
We’re missing a space.
Python is completely literal when working with strings.
We need to explicitly include spaces and
punctuation if we want what we write to make sense.
This time we got a string that makes sense,
putting the two words together with a space in between.
Note that previously I said a white space doesn’t matter in
between parentheses in bits of code, like print statements.
Here with strings, you can see that spaces do matter in between the quotation marks.
Let’s try another mathematical operation.
Turns out we can use the multiplication operator as well.
It repeats the string as many times as you multiply it.
Here five times.
Although addition and multiplication have different applications for strings,
subtraction and division do not.
Here we get an error that a string is an unsupported type for the division operator.
A useful function that’s built into Python
is Len which can tell us the length of a string.
This is just the number of characters in the string.
Len is like print in that it’s a built-in function that
takes in a value in parentheses to perform an action.
Len differs from print in that it returns a value that can be stored in a variable.
In this example, the Len function outputs to number seven,
which is stored in the Udacity length variable.
Built-in just means Python provides these functions for us.
Later, we’ll learn how to define our own functions.
종종 프로그래밍에는 숫자와 산술 이상의 것이 포함됩니다.
텍스트로 작업해야 하는 상황이 있을 수 있습니다.
파이썬에서 텍스트로 작업하려면,
문자열을 사용해야 합니다.
이는 변경할 수 없는 일련의 문자입니다.
변경할 수 없는 순서 부분에 대해서는 나중에 자세히 설명합니다.
따옴표를 사용하여 문자열을 만들 수 있습니다.
작은따옴표나 큰따옴표는 똑같이 잘 작동합니다.
일부 극단적인 경우가 있지만 우리는 이를 해결해 나갈 것입니다.
이 각각의 경우에 “hello”라는 문자열을 출력하고 “hello”라는 출력을 얻었습니다.
숫자와 같은 방식으로 변수를 문자열로 설정할 수 있습니다.
문자열은 모든 문자를 포함할 수 있으며,
심지어 공백, 구두점 및 숫자.
그러나 문자열에 따옴표가 필요하면 어떻게 해야 합니까?
문자열을 정의하기 위해 따옴표를 사용하기 때문에
이것은 작은 문제를 나타냅니다.
여기서 코드는 우리가 원하는 방식으로 작동하지 않습니다.
Python은 이 문제에 대해 두 가지 솔루션을 제공합니다.
첫 번째는 이와 같이 큰따옴표가 아닌 작은따옴표로 문자열을 배치하는 것입니다.
두 유형의 따옴표를 사용하여 문자열을 정의할 수 있습니다.
그러나 때로는 작은따옴표와 큰따옴표를 모두 포함하는 문자열을 정의해야 합니다.
그럼? 그 경우,
백슬래시를 사용하여 따옴표를 이스케이프할 수 있습니다.
여기서 문자열은 작은따옴표로 구분됩니다.
문자열 내의 작은 따옴표 앞에는 백슬래시가 붙어서 파이썬이
의 일부로 해석되어야 함을 알고 있습니다.
문자열을 끝내는 따옴표가 아닌 문자열입니다.
문자열이 정의되면
에 사용되는 몇 가지 작업이 있습니다.
문자열에도 사용할 수 있는 정수 및 부동 소수점.
예를 들어 더하기 기호를 사용하여 문자열을 결합할 수 있습니다.
곱하기를 사용하여 문자열을 반복할 수 있습니다.
각각의 예를 살펴보겠습니다.
여기서 우리의 변수는 두 단어를 담고 있습니다.
더하기 기호를 사용하여 두 문자열을 연결하고 결과를 인쇄할 수 있습니다.
이것은 숫자 덧셈과 근본적으로 다릅니다.
그러나 두 이름이 함께 뭉개졌습니다.
공간이 부족합니다.
파이썬은 문자열로 작업할 때 완전히 리터럴입니다.
명시적으로 공백을 포함해야 하고
우리가 쓰는 것이 의미가 있기를 원한다면 구두점.
이번에는 의미가 있는 문자열을 얻었습니다.
두 단어를 사이에 공백으로 연결합니다.
이전에 공백은 중요하지 않다고 말했습니다.
print 문과 같이 코드 비트의 괄호 사이.
여기에서 문자열을 사용하면 따옴표 사이에 공백이 중요하다는 것을 알 수 있습니다.
다른 수학 연산을 시도해 보겠습니다.
곱셈 연산자도 사용할 수 있습니다.
곱한 만큼 문자열을 반복합니다.
여기 다섯 번.
덧셈과 곱셈은 문자열에 대한 다른 응용 프로그램이 있지만
뺄셈과 나눗셈은 하지 않습니다.
여기서 문자열이 나누기 연산자에 대해 지원되지 않는 유형이라는 오류가 발생합니다.
Python에 내장된 유용한 함수
문자열의 길이를 알 수 있는 Len입니다.
이것은 문자열의 문자 수입니다.
Len은 내장 함수라는 점에서 print와 같습니다.
작업을 수행하기 위해 괄호 안의 값을 취합니다.
Len은 변수에 저장할 수 있는 값을 반환한다는 점에서 print와 다릅니다.
이 예에서 Len 함수는 7번으로 출력합니다.
Udacity 길이 변수에 저장됩니다.
내장은 Python이 이러한 기능을 제공한다는 것을 의미합니다.
나중에 우리는 우리 자신의 함수를 정의하는 방법을 배울 것입니다.
"
followed by single quotes '
.
Strings
Strings in Python are shown as the variable type str
. You can define a string with either double quotes "
or single quotes '
. If the string you are creating actually has one of these two values in it, then you need to be careful to assure your code doesn’t give an error.
>>> my_string = 'this is a string!' >>> my_string2 = "this is also a string!!!"
You can also include a \
in your string to be able to include one of these quotes:
>>> this_string = 'Simon\'s skateboard is in the garage.' >>> print(this_string)
Simon's skateboard is in the garage.
If we don’t use this, notice we get the following error:
>>> this_string = 'Simon's skateboard is in the garage.'
File "<ipython-input-20-e80562c2a290>", line 1 this_string = 'Simon's skateboard is in the garage.' ^ SyntaxError: invalid syntax
The color highlighting is also an indication of the error you have in your string in this second case. There are a number of other operations you can use with strings as well. In this video you saw a few:
>>> first_word = 'Hello' >>> second_word = 'There' >>> print(first_word + second_word) HelloThere >>> print(first_word + ' ' + second_word) Hello There >>> print(first_word * 5) HelloHelloHelloHelloHello >>> print(len(first_word)) 5
Unlike the other data types you have seen so far, you can also index into strings, but you will see more on this soon! For now, here is a small example. Notice Python uses 0 indexing – we will discuss this later in this lesson in detail.
>>> first_word[0] H >>> first_word[1] e
The len()
function
len()
is a built-in Python function that returns the length of an object, like a string. The length of a string is the number of characters in the string. This will always be an integer.
There is an example above, but here’s another one:
print(len("ababa") / len("ab")) 2.5
You know what the data types are for len(“ababa”) and len(“ab”). Notice the data type of their resulting quotient here.
댓글을 달려면 로그인해야 합니다.