Working with strings
Letters have positions
- A string is a row of characters.
- Each character has a position, called an index.
- Indexes start at
0. Uses[-1]for the last character.
문자에는 위치가 있습니다
- 문자열은 문자들의 나열입니다.
- 각 문자에는 인덱스라고 불리는 위치가 있습니다.
- 인덱스는
0에서 시작합니다. 마지막 문자를 위해s[-1]을 사용하십시오.
word = "Python"
print(word[0])
print(word[-1])
Take a slice
- A slice takes part of a string:
s[start:end]. - The character at
endis not included. - Leave a side empty for "from the start" or "to the end":
s[:3],s[2:].
슬라이스 가져오기
- 슬라이스는 문자열의 일부를 가져옵니다:
s[start:end]. end에 해당하는 문자는 포함되지 않습니다.- "시작부터" 또는 "끝까지"를 의미하려면 한쪽을 비워두십시오:
s[:3],s[2:].
msg = "hello"
print(msg[:3])
print(msg[2:])
Worked example: positions and slices
- In
"banana"the positions areb=0,a=1,n=2,a=3,n=4,a=5. word[0]is the first letter;word[-1]counts back from the end.word[:3]takes positions 0, 1 and 2, and stops before 3.
풀이 예제: 위치와 슬라이스
"banana"에서의 위치는b=0,a=1,n=2,a=3,n=4,a=5입니다.word[0]은 첫 번째 문자이며;word[-1]은 끝에서 세어갑니다.word[:3]은 위치 0, 1, 2를 가져오고 3보다 앞에서 멈춥니다.
word = "banana"
print(word[0]) # b
print(word[-1]) # a (the last letter)
print(word[:3]) # ban (positions 0, 1, 2)
print(word[2:5]) # nan (positions 2, 3, 4)
Length and changing case
len(s)gives the number of characters.s.upper()makes a CAPITAL copy;s.lower()makes a lowercase copy.- These make a new string; the original does not change.
길이와 대/소문자 변경
len(s)는 문자 수를 반환합니다.s.upper()은 대문자 복사본을 만듭니다;s.lower()은 소문자 복사본을 만듭니다.- 이들은 새로운 문자열을 생성하며, 원본은 변하지 않습니다.
city = "Tokyo"
print(len(city))
print(city.upper())
print(city.lower())
f-strings build text
- An f-string starts with
fbefore the quote. - Put a value inside
{ }and Python drops it into the text. - It is the neat way to mix words and values.
f-strings로 텍스트 만들기
- f-string은 따옴표 앞에
f으로 시작합니다. { }안에 값을 넣으면 Python이 이를 텍스트에 삽입합니다.- 이는 단어와 값을 섞는 깔끔한 방법입니다.
fruit = "apple"
count = 3
print(f"I have {count} {fruit}s")
Common mistakes
- Indexing starts at
0;s[-1]is the last character. - Strings cannot be changed in place — methods like
.upper()return a NEW string, so store the result. - You can only join a string to a string with
+.
흔한 실수
- 인덱싱은
0에서 시작하며;s[-1]은 마지막 문자입니다. - 문자열은 위치에서 변경할 수 없습니다 —
.upper()과 같은 메서드는 새로운 문자열을 반환하므로 결과를 저장하십시오. +으로 문자열끼리만 연결할 수 있습니다.
Now you try
- Read the task to see which variable to fill or what to print.
- Press Check answer to test your code.
이제 직접 해보기
- 어떤 변수를 채우거나 무엇을 출력해야 하는지 보려면 작업을 읽어보십시오.
- Answer 확인 버튼을 눌러 코드를 테스트하세요.
Index & slice a string
Each character has an index from 0; a slice s[a:b] takes a range.
word is "computer". Store its first character in first. Indexes start at 0, so that character is word[0].
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
first is already the first character of "computer". Store the first four characters in first_four with a slice. word[a:b] stops before b, so four characters is word[:4].
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
phrase is "Hello World". Store its length in n with len(...), and an UPPERCASE copy in loud with .upper().
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
name is "Mia" and age is 12. Use an f-string to print exactly: Mia is 12 years old.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
first is "ada" and last is "lovelace". Store the initials in initials as capital letters, each followed by a dot: "A.L.".
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.