formatting, split

모서아·2024년 12월 16일

파이썬 복습공책

목록 보기
4/5

우선 과제풀면서 제일 궁금했던 거
포맷팅 ! 과제하면서 자료를 많이 찾다보니 다들 print(f "") 를 많이 쓰길래 구글링을 열심히 했는데 이게 포맷팅인지도 모르고 f .. f.... 이거 f 뭐지 ..? 왜 쓰는거지 ..? 찾다가 오늘 찾아버렸다 강의에서 찾아버렸다 완전 럭키비키니시티. 😆

포맷팅 (formatting)

f-string
x = 10
print(f"변수 x의 값은 {x}입니다.")
x = 10
print("변수 x의 값은 {}입니다.".format(x))
x = 10
print("변수 x의 값은 %d입니다." % (x))

split

문자열 → 리스트로 변환 (공백 기준으로 분할)

sentence = "Hello, how are you doing today?"
words = sentence.split()
print(words)  # 출력: ['Hello,', 'how', 'are', 'you', 'doing', 'today?']

(특정 구분자를 기준으로)

data = "apple,banana,grape,orange"
fruits = data.split(',')
print(fruits)  # 출력: ['apple', 'banana', 'grape', 'orange']코드를 입력하세요

리스트의 각 항목을 문자열로 (알고만 있는 걸로)

words = ['Hello,', 'how', 'are', 'you', 'doing', 'today?']
sentence = ' '.join(words)
print(sentence)  # 출력: Hello, how are you doing today?

리스트의 각 항목을 문자열로 결합하되, 특정 구분자를 사용하여 결합

fruits = ['apple', 'banana', 'grape', 'orange']
data = ','.join(fruits)
print(data)  # 출력: apple,banana,grape,orange

여러 줄로 이루어진 문자열을 줄 단위로 분할하여 리스트로 변환하기

text = """First line
Second line
Third line"""
lines = text.split('\n')
print(lines)  # 출력: ['First line', 'Second line', 'Third line']

문자열을 공백으로 분할한 후 특정 개수의 항목만 가져오기

sentence = "Hello, how are you doing today?"
words = sentence.split()
first_three_words = words[:3]
print(first_three_words)  # 출력: ['Hello,', 'how', 'are']

문자열에서 공백을 제거한 후 문자열을 리스트로 변환하기

text = "   Hello   how   are   you   "
cleaned_text = text.strip()
words = cleaned_text.split()
print(words)  # 출력: ['Hello', 'how', 'are', 'you']

split 실전 예시

# 데이터의 경로를 문자열로 표현
file_path = "/usr/local/data/sample.txt"

# split() 함수를 사용하여 디렉토리와 파일명으로 분할
directory, filename = file_path.rsplit('/', 1)
print("디렉토리:", directory)  # 출력: 디렉토리: /usr/local/data
print("파일명:", filename)    # 출력: 파일명: sample.txt
  • 예시에서는 file_path라는 문자열 변수에 데이터의 경로를 저장하고, split() 함수를 사용하여 문자열을 / 기준으로 분할합니다.
  • 이때, rsplit() 함수를 사용하여 오른쪽에서부터 최대 1회만 분할하도록 설정하여 파일명과 디렉토리로 나눕니다.
  • 분할된 결과를 각각 directory와 filename 변수에 할당하여 출력합니다.

0개의 댓글