728x90
<리스트 요소 교체>
>>> print('Hello World!'.replace('World', 'Python'))
Hello Python!
** .replace(): 문자열에서 특정 문자열을 교체
. 앞에 있는 것을 괄호 안의 것으로 교체
a = 'Hello World!'
>>> print(a.replace('World', 'Python'))
Hello Python!
>>> print('홍길동*&^%^%^'.replace('*&', '')) // *&을 ''로 바꿔라
홍길동^%^%^
>>> table = str.maketrans('aeiou', '12345')
a=1 e=2 i=3 o=4 u=5
** str.maketrans(원래문자, 바꿀문자): 원래 문자에 다른 문자를 대입할 때 사용 (문자, 숫자 가능)
a=1 e=2 i=3 o=4 u=5
>>> print('apple'.translate(table))
>>> print('apple'.translate(str.maketrans('aeiou', '12345'))) // 동일한 과정
1ppl2
** ''.translate(): 문자만 변환 가능
** ''.zfill(숫자): 괄호 안에 지정한 숫자만큼 0을 채움
>>> print('"', '35.0'.zfill(7), '"', sep='')
"00035.0"
>>35.0이 총 일곱글자가 되도록 0을 채워라.
>>> print('"', 'python'.zfill(10), '"', sep='')
"0000python"
** ''.upper() / ''.lower()
1. ''.upper(): 소문자를 대문자로 바꿈
2. ''.lower(): 대문자를 소문자로 바꿈
>>> print('apple'.upper())
APPLE
>>> print('APPLE'.lower())
apple
<리스트 요소 합체 및 분리>
>>> print('apple pear grape pineapple orange'.split())
['apple', 'pear', 'grape', 'pineapple', 'orange']
** ''.split(): 하나의 문자열을 일정한 기준으로 잘라서 개별의 리스트 요소로 만드는 함수
자르는 기준은 괄호 안에 있는 것
>> 리스트 요소 자르기
>>> print('apple, pear, grape, pineapple, orange'.split(','))
['apple', 'pear', 'grape', 'pineapple', 'orange']
>>> print(type('2023/12/29'.split('/')))
['2023', '12', '29']
>>> print(', '.join(['apple', 'pear', 'grape', 'pineapple', 'orange']))
** join(): 배열의 모든 요소를 연결해 하나의 문자열로 만들어 줌
[](리스트) 안에 있는 요소를 join 앞에 있는 ,으로 연결해 하나의 문자열로 생성
>> 리스트 요소 합체
apple, pear, grape, pineapple, orange
>>> print(type''.join(['apple', 'pear', 'grape', 'pineapple', 'orange']))
<class 'list'>
>> 종류 확인해 보면 list로 뜸
<문자열 찾기>
** ''.find(): 괄호 안의 글자를 '' 안에서 찾아 몇 번째에 있는지 표현해줌
없으면 -1을 출력함. 첫번째 글자를 0부터 센다. (0번째, 1번째,...)
print('python'.find('h'))
3
print('python'.find('A'))
-1
print('python'.rfind('p'))
0
** .index(): 배열에서 찾고자 하는 값의 인덱스 위치를 알려주는 함수
>>> print('python'.index('y'))
1
>>> print('python'.index('A'))
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
print('python'.index('A'))
ValueError: substring not found
**>> 찾는 문자열이 없을 경우 에러 발생 (그에 비해 find 함수는 -1로 출력)**
** .rindex(): 괄호 안의 문자열이 마지막으로 나오는 위치 출력
>>> print('python'.rindex('P'))
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
print('python'.rindex('P'))
ValueError: substring not found
**>> 찾는 문자열이 없을 경우 에러 발생**
>>> print('apple pineapple'.count('pl'))
2
>> 글자가 두 글자일 경우, 해당 단어를 묶 한 글자로 생각함
<리스트 요소 가독성 정리>
** ''.strip(): 불필요한 공백 제거
1. ''.rstrip(): 문자 왼쪽의 공백 제거
2. ''.lstrip():문자 오쪽의 공백 제거
>> 괄호 안에 문자를 넣으면 해당 문자와 동일한 것 모두 제거
>>> print(' Python '.lstrip())
Python
>>> print(' Python '.rstrip())
Python
>>> print(' Python '.strip())
Python
>>> print(', Python. '.rstrip(',. '))
, Python
** ''.rjust(숫자) : 문자열을 오른쪽으로 n만큼 정렬
** ''.ljust(숫자) : 문자열을 왼쪽으로 n만큼 정렬
>> 가운데 정렬할 때 사용
>>> print('"', 'python'.ljust(10), '"', sep='')
"python "
>>> print('"', 'python'.rjust(10), '"', sep='')
" python"
<포매팅> 서식 지정자
- 문자열 안에 어떤 값이나 변수 따위를 삽입하는 방법
- %s = 문자열, %d = 정수, %f = 실수
>>> name = 'Son'
>>> print('I am %s.' % name)
I am Son.
>>> print('%s님의 정보가 저장되었습니다.' % name)
Son님의 정보가 저장되었습니다.
>>> print('I am %d years old.' % 20)
I am 20 years old.
** %f: % 뒤에 있는 숫자를 실수로 만들어 삽입해라.
기본적으로 소수점 6자리 이하까지 표현되고, 개수를 지정하려면 %(숫자)f 형식으로 표현
>>> print('%f' % 3.14)
3.140000
>>> print('%.7f' % 3.14)
3.1400000
>>> print('Today is %2d %s.' % (3, 'April'))
Today is 3 April.
** .format(): 문자열에 특정 변수의 값을 넣을 때 사용
>>> print('Hello {0}, {1}'.format('World', '!'))
Hello World, !
>> {0}='World' {1}='!'
>>> print('Hello {1}, {0}'.format('World', '!'))
Hello !, World
** 숫자로 지정해 문자열을 삽입할 시, 함수의 길이가 길어지기 때문에, 변수를 지정해 대신 삽입
이럴 땐 **print(f) 사용**
>>> world = 'World'
>>> b = '!'
>>> language = 'Python'
>>> print('Hello {1}, {0}, {1}, {0}'.format(world, b))
Hello !, World, !, World
>>> version = '3.11'
>>> print(f'Hello, {language}, {version}, {language}, {version}')
Hello, Python, 3.11, Python, 3.11
'프로그래밍 언어 > Python' 카테고리의 다른 글
파이썬 Python 실습 :: 기본적인 파일 사용 정리 함수 (0) | 2024.01.10 |
---|---|
파이썬 Python 실습 :: 딕셔너리 실습 (키와 값) (1) | 2024.01.09 |
파이썬 Python 실습 :: 리스트 심화 실습 (요소 추가, 삭제, 수정, 복사) (0) | 2024.01.04 |
파이썬 Python 실습 :: 반복문 for, while 실습 (1) | 2024.01.04 |
파이썬 Python 실습 :: 조건문 if, else, elif 간단 정리 (0) | 2024.01.04 |