Backend/Python

Python 파이썬 데이터 저장 공간 : for문, 문자열, 인덱스(index)

쏠솔랄라 2023. 6. 30. 11:58

 

 

파이썬 데이터 저장 공간

 

: 여러개의 데이터들을 저장하는 공간들 ; 문자열, 튜플, 리스트, 딕셔너리

 

 


 

 

데이터 저장 공간과 for문

 

 

for i in range(10,5,-2):
    print("i = {}".format(i))


for문을 통해서 하나씩 추출하여 사용할 수 있다

 

출력화면

 

ex.

 

for i in "abcdef":
    print(i)

name = "김모씨"
for i in name:
    print(i)

for i in [1,2,3,4,5]:
    print(i)

 

출력화면

 

 

인덱스 index

 

: 연속적인 공간들을 구별하기위해서 붙여놓은 번호
(C언어에서의 포인터와 관련)
항상 0부터 시작한다 ; 가장 마지막 요소는 크기보다 1이 작다



인덱스 사용형식 : 여러개의 데이터를 저장하는 공간에서만 사용 가능

e.g. [인덱스]

print("abcdefg"[0])
s = "abcdefg"


인덱싱 : 인덱스값 위치의 있는 데이터를 추출하는 역할

print(s[5])
print(s[-1])


슬라이싱 : 인덱스 범위를 지정해서 사이에 있는것들을 추출하는 역할
m 부터 n이전까지

e.g. s[m:n]

print(s[1:3]) # 1 ~ 3이전까지
print(s[1:-1]) # 1 ~ -1이전까지
print(s[:5]) # 시작부터 5이전까지
print(s[5:]) # 5부터 끝까지


슬라이싱을 이용해서 날짜와 시간을 분리 하여 출력

date = "2022년 7월 29일 오전 11시 5분"
print(date[0:12])
print(date[13:])

 

출력화면

 

 

문자열 메소드

 

 

find(문자열)

: 문자열에서 특정 문자열을 찾아 해당 문자의 index값을 반환

 

mail = "abcdefg@email.com"

# 검색한 문자열이 있으면 인덱스값 반환, 없으면 -1반환
print(mail.find("dark"))
print(mail.find(".com"))
print(mail.find(".cm"))

# 이 문자열로 끝나느냐
print(mail.endswith(".com")) 
print(mail.endswith("abc"))

# 이문자열로 시작하느냐
print(mail.startswith(".com")) 
print(mail.startswith("abc"))

# 문자열의 길이값
print(mail.__len__()) # 문자열 길이
print(mail.__sizeof__()) # 객체의 크기를 byte단위로 변환

# count(문자열) : 해당 문자열의 개수 반환
print(mail.count('a')) 
print(mail.count('@'))
print(mail.count('y'))

# 메소드나 함수명에 is가 붙으면 ~이다 ~있냐 
print(mail.islower()) # 소문자냐
print(mail.isupper()) # 대문자냐
print(mail.isalpha()) # 알파벳이냐
print(mail.isdigit()) # 숫자냐

#대문자 -> 소문자 , 소문자 -> 대문자
print(mail.upper()) # 대문자로 변환
print(mail.lower()) # 소문자로 변환
print(mail.swapcase()) # 대문자는 소문자로 소문자는 대문자로 변환

 

출력화면

-1
13
-1
True
False
False
True
17
66
2
1
0
True
False
False
False
ABCDEFG@EMAIL.COM
abcdefg@email.com
ABCDEFG@EMAIL.COM
    askldfjl   asdsdajhlfkjasd      
37
askldfjl   asdsdajhlfkjasd
26
askldfjl   asdsdajhlfkjasd      
33
    askldfjl   asdsdajhlfkjasd
30
askldfjl   asdsdajhlfkjasd
SAkldfjl   SAdsdajhlfkjSAd
['A', 'B', 'C', 'D-E', 'F', 'G']
['A/B/C/D-E/F/G']
A-B-C-D-E-F-G

 

 

ex1.

text = "    askldfjl   asdsdajhlfkjasd       "
print(text)
print(text.__len__())

# 공백제거
print(text.strip()) # 앞뒤 공백제거
print(text.strip().__len__())
print(text.lstrip()) # 앞 공백제거
print(text.lstrip().__len__())
print(text.rstrip()) # 뒤 공백제거
print(text.rstrip().__len__())

text = text.strip()
print(text)
print(text.replace("as","SA"))# 문자열 치환

 

출력화면

    askldfjl   asdsdajhlfkjasd      
37
askldfjl   asdsdajhlfkjasd
26
askldfjl   asdsdajhlfkjasd      
33
    askldfjl   asdsdajhlfkjasd
30
askldfjl   asdsdajhlfkjasd
SAkldfjl   SAdsdajhlfkjSAd

 

 

ex2.

rainbow = "A/B/C/D-E/F/G"

print(rainbow.split('/')) # 문자열 분리
print(rainbow.splitlines(1))
print("-".join("ABCDEFG")) # 문자열 삽입

 

출력화면

['A', 'B', 'C', 'D-E', 'F', 'G']
['A/B/C/D-E/F/G']
A-B-C-D-E-F-G

 

 

ex3.

name = "Adele"

print(type(name))
print(name)

song = """
There's a fire starting in my heart
Reaching a fever pitch and it's bringing me out the dark
Finally, I can see you crystal clear
Go ahead and sell me out and I'll lay your sheet bare
See how I'll leave with every piece of you
Don't underestimate the things that I will do
There's a fire starting in my heart
Reaching a fever pitch and it's bringing me out the dark
The scars of your love remind me of us
They keep me thinking that we almost had it all
The scars of your love, they leave me breathless
I can't help feeling
we could have had it all
(You're gonna wish you never had met me)
Rolling in the deep
(Tears are gonna fall, rolling in the deep)
You had my heart inside of your hands
(You're gonna wish you never had met me)
And you played it to the beat
(Tears are gonna fall, rolling in the deep)
"""

print(song)

 

출력화면

 

''' ''' 또는 """ """ 은 주석 처리 외에 문자열 처리 기능이 있다