AI/Python
[Python] 문자열의 메소드, 문자열을 숫자로, 지수표현
brave_sol
2025. 3. 27. 13:14
1. 검사
- str.isdigit() : 숫자인지 확인(공백, 기호, 알파벳, 소수점 등은 모두 허용하지 않음)
print("1234".isdigit()) # True
print("1234a".isdigit()) # False
print("".isdigit()) # False (빈 문자열)
print("1 2 3 4".isdigit()) # False (공백있으면 안됨)
print("1234".isdigit()) # True (ㅈ+한자로 입력한 특수문자(유니코드 숫자)
- isalpha() : 알파벳인지
- isalnum(): 알파벳+숫자인지
- isspace(): 공백"만" 있는지(공백 개수 상관 없음)
print(' '.isspace()) # True
print(' '.isspace()) # True
print(' .. '.isspace()) # False
- startswith(x): x로 시작하는지
- endswith(x): x로 끝나는지
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("123".isalnum()) # True
print("abc123".isalnum()) # True
print("1 23".isspace()) # False
print(" ".isspace()) # True
print("apple".startswith('a')) # True
print("apple".endswith('e')) # True
2. 대소문자 관련
- lower() : 소문자로
- upper(): 대문자로
- capitalize(): 첫 글자만 대문자
print('Hello'.lower()) # hello
print('Hello'.upper()) # HELLO
print('hello bye'.capitalize()) # Hello bye
3. 자르기/나누기
- split() : 공백 또는 지정문자 기준으로 나누기 => 리스트로 반환
s= "try hello world"
print(s.split())
# ['try', 'hello', 'world'] #공백은 갯수 상관없음
s= " try hello world "
print(s.split())
# ['try', 'hello', 'world'] # 좌우 공백도 무시
s= "try hello world"
print(s.split(' ')) # 정확히 공백 1개 기준으로 나눔
# ['try', 'hello', '', 'world'] # 하지만 hello world 사이에 공백 2개인데 1개만 알려줌
s= "try.hello..world"
print(s.split('.'))
# ['try', 'hello', '', 'world'] # 점 기준으로 나눔
- strip(): 앞 뒤 공백 제거
- lstrip(), rstrip(): 왼쪽/오른쪽 공백제거
print(' He llo '.split()) # ['He', 'llo']
print(' He llo '.strip()) # He llo
print(' He llo '.lstrip()) # He llo
print(' He llo '.rstrip()) # He llo
4. 기타
- join(list): 리스트를 문자열로 합치기
- find(x) : x가 처음 나타나는 위치
- count(x): x가 몇 번 나오는지
print('-'.join(['a','b'])) # a-b
print('hello'.find('l')) # 2
print('banana'.count('a')) # 3
5. 문자열을 숫자로, 지수표현
- e는 파이썬 문법에서 지수표현을 의미, 1e6은 1*10^6 , 즉 e=10** (자연상수 e=2.718..아님 주의!, 자연상수는 math.e)
print(int(1e6)) # 1000000(10^6)
print(1e6) # 1000000.0
print(10**6 == 1e6) # True
# print(int('1e6')) # invalid literal for int() with base 10: '1e6'
print(float('1e6')) # 1000000.0
print(int(float('1e6'))) # 1000000
- int는 문자열을 받을때 정수만 받는데, 지수표현을 사용하면 실수가 되서 실수로 변환 후 int를 사용해야함
반응형