상세 컨텐츠

본문 제목

[파이썬 6강] 스트링과 딕셔너리

로봇-AI

by happynaraepapa 2025. 1. 3. 11:20

본문

source:
https://www.kaggle.com/code/colinmorris/strings-and-dictionaries

Strings and Dictionaries

Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources

www.kaggle.com


Strings 스트링: 문자열
One place where the Python language really shines is in the manipulation of strings. This section will cover some of Python's built-in string methods and formatting operations.
파이썬의 내장된 문자열 메소드(built-in string methods)와 형식 연산자(formatting operations)에 대해서 기술.

Such string manipulation patterns come up often in the context of data science work.
이러한 문자열 조작 패턴은 데이터 사이언스 작업에 자주 활용됨.

String syntax
문자열 구조
You've already seen plenty of strings in examples during the previous lessons, but just to recap, strings in Python can be defined using either single or double quotations. They are functionally equivalent.
이전 예제에서 다양한 문자열을 봤을테지만 다시 상기시킨다면 파이썬에서는 문자열을 작은 따옴표 또는 큰 따옴표로 묶어 정의한다. (둘 다 동일하다.)

Double quotes are convenient if your string contains a single quote character (e.g. representing an apostrophe).
Similarly, it's easy to create a string that contains double-quotes if you wrap it in single quotes:
만약 쓰려는 문자열이 작은따옴표를 가지고 있다면 큰 따옴표를 써서 문자열을 정의해야 한다. 반대의 경우에는 작은 따옴표를 써서 정의하면 된다.

If we try to put a single quote character inside a single-quoted string, Python gets confused:
만약 이를 혼용하면 에러가 난다.

We can fix this by "escaping" the single quote with a backslash.
이런 에러가 난 경우, 우리는 작은따옴표에 백슬래쉬를 줘서 'escaping 이스케이핑' 시킬 수 있다.
>>
'Pluto\'s a planet!'
>>
"Pluto's a planet!"


The table below summarizes some important uses of the backslash character.
아래 테이블은 몇가지 중요한 백슬래쉬 이스케이핑 문자들을 보여준다.

The last sequence, \n, represents the newline character. It causes Python to start a new line.
'\n'은 newline character 라고 한다. (줄바꿈문자)

In addition, Python's triple quote syntax for strings lets us include newlines literally (i.e. by just hitting 'Enter' on our keyboard, rather than using the special '\n' sequence). We've already seen this in the docstrings we use to document our functions, but we can use them anywhere we want to define a string.
추가로 파이썬은 인용부호를 3개 사용하는 문법이 있으며 이경우는 '\n'을 사용하지 않고도 콘솔 화면상에 줄바꿈이 일어나도록 한다.
우리는 이미 앞선 예제의 docstrings에서 이것이 사용된 예를 보았다.

The print() function automatically adds a newline character unless we specify a value for the keyword argument end other than the default value of '\n':
print() 함수는 디폴트로 '\n'을 newline character로 정해놓았고, 별도로 지정하지 않는다면 이 값을 자동으로 문장 끝에 더한다.

...
Strings are sequences
Strings can be thought of as sequences of characters. Almost everything we've seen that we can do to a list, we can also do to a string.
Strings는 문자의 연속계로 볼 수 있고, 그래서 문자열이라고 한다. 리스트에 했던 대부분의 것을 할 수 있다.

# Indexing 인덱싱

# Slicing 슬라이싱

# How long is this string? 크기/길이

# Yes, we can even loop over them 루프 해석 loop comprehension

But a major way in which they differ from lists is that they are immutable. We can't modify them.
하지만 리스크가 다른점 중 하나는 수정이 불가하다는 점이다.
>>
TypeError: 'str' object does not support item assignment

String methods
문자열 메소드

Like list, the type str has lots of very useful methods. I'll show just a few examples here.
리스트와 마찬가지로 str 타입은 다양하게 활용가능한 메소드가 있고 몇가지 예를 들면,
....
Going between strings and lists: .split() and .join()
문자열과  리스트 사이를 오가면?
str.split() turns a string into a list of smaller strings, breaking on whitespace by default. This is super useful for taking you from one big string to a list of words.
str.splitI()은 문자열을 쪼개서 리스트로 만든다. 디폴트로 스페이스(띄어쓰기) 기준으로 나눈다.
이는 하나의 긴 문자열을 워드(단어)단위로 나누어 분할하는데 매우 유용하다.
...
Occasionally you'll want to split on something other than whitespace:
쪼개는 기준(separator: 구분자??)은 스페이스 외에도 지정 가능하다.

...

str.join() takes us in the other direction, sewing a list of strings up into one long string, using the string it was called on as a separator.
str.join()은 반대로 여러 작은 문자열을 하나의 긴 문자열로 바꿔준다. 이때 separator를 지정할 수 있다.

If we want to throw in any non-string objects, we have to be careful to call str() on them first
문자가 아닌 캐릭터들을 배제하려면 메소드 사용시 주의하자.
...
This is getting hard to read and annoying to type. str.format() to the rescue.
이 문장은 읽기가 어렵다. 이런경우 str.format()을 사용할 수 있다.
...
So much cleaner! We call .format() on a "format string", where the Python values we want to insert are represented with {} placeholders.
훨씬 읽기가 쉬워졌다. .format() 메소드는 {}로 표시된 위치에 원하는 값을 집어 넣기 위한 메소드다.

Notice how we didn't even have to call str() to convert position from an int. format() takes care of that for us.
변환과정이 생략되어 매우 편리했음

If that was all that format() did, it would still be incredibly useful. But as it turns out, it can do a lot more. Here's just a taste:
단순히 이것만 가지고도 format()메소드가 유용하지만, 그 외에도 여러가지 활용이 있다. 아래 예시.

...
You could probably write a short book just on str.format, so I'll stop here, and point you to pyformat.info and the official docs for further reading.
너무 많아서 str.format()에 대한 짧은 책을 써야 할 정도이므로 여기서 멈춘다. 추가적인 내용은 공식 문건을 찾아보라.

Dictionaries 딕셔너리
Dictionaries are a built-in Python data structure for mapping keys to values.
딕셔너리는 파이썬에 내장된 데이터 구조체로 key-value로 매핑되어 있다.
...
In this case 'one', 'two', and 'three' are the keys, and 1, 2 and 3 are their corresponding values.
여기서 'one', 'two', 'three'는 키key이고, 1,2,3은 이에 상응되는 value 값들이다.

Values are accessed via square bracket syntax similar to indexing into lists and strings.
리스트나 문자열에서 인덱싱하듯이 []를 이용한 인덱싱을 한다.
>>
numbers['one']
1


We can use the same syntax to add another key, value pair
같은 방법으로 key-value 쌍을 더할 수도 있다.

Or to change the value associated with an existing key
또는 기존 key값에 매칭된 value 변경도 가능하다.

Python has dictionary comprehensions with a syntax similar to the list comprehensions we saw in the previous tutorial.
리스트 해석(list comprehension)과 동일하게 딕셔너리 해석(dictionary comprehension)도 가능하다.

...
The in operator tells us whether something is a key in the dictionary
'in' 연산자가 딕셔너리 내의 key 여부를 알려준다.
...
A for loop over a dictionary will loop over its keys
딕셔너리를 이용하여 loop를 걸면 그 key에 대한 루프가 실행된다.
...
We can access a collection of all the keys or all the values with dict.keys() and dict.values(), respectively.
딕셔너리의 key 집합과 value 집합은 각각 dick.keys()와 dict.values()로 조회된다.

..
The very useful dict.items() method lets us iterate over the keys and values of a dictionary simultaneously. (In Python jargon, an item refers to a key, value pair)
dict.items() 메소드는 key-value 쌍을 조회한다.

...
To read a full inventory of dictionaries' methods, click the "output" button below to read the full help page, or check out the official online documentation.
딕셔너리의 모든 메소드를  보려면 공식 문건을 참조.

....

'로봇-AI' 카테고리의 다른 글

[파이썬8강] Gemini 2.0  (0) 2025.01.06
[파이썬7강] Working with External Libraries  (0) 2025.01.06
[파이썬 5강]Loops and List comprehension  (0) 2024.12.31
[파이썬 제4강] Lists  (0) 2024.12.30
[파이썬3강]Booleans  (0) 2024.12.27

관련글 더보기