Python Day 6文字列式、文字列関数


復習Day 5


Day 5復習&Day 6学習材料

1-1)list 1出力例を使用します。物価上昇で買い値が変更され、紅脂商会も利益や販売価格を更新してみた。リスト1の各金額に10%反映された金額を小数第1位から四捨五入しprint関数として出力してください。

출력예시
할인가격 : 2040 새 이윤: 40
할인가격 : 3400 새 이윤: 0
할인가격 : 55200 새 이윤: 1200
#원가, 이윤, 판매가격이 있는 리스트이다.
list1 = [
    [ 2000,  550,  2550],
    [ 3400,  850,  4250],
    [54000, 15000, 69000]
]
for i in list1:
    print("할인가격: {0} 새 이윤: {1}".format(round(i[2]*0.9), round((i[2]*0.9))-i[0]))

1-2)物価上昇により購入価格が変化し,紅脂商会も利益と販売価格の更新を試みた。リスト1の利益と販売価格に金額の10%をそれぞれ反映し、リスト1で少数の1位から四捨五入してから再保存してください。

for i in list1:
    i[2] = round(i[2]*1.1)
    i[1] = round((i[2]*1.1))-i[0]
print(list1)

1−3)口紅商会の帳簿list 1の最初の順序として、「原価」、「利益」、「販売金額」の内容を含むリストを追加する。追加後、完全なリストを印刷します。

list1.insert(0, ['원가', '이윤', '판매금액'])

1−4)紅商会は新年を迎えるため,5000元以下の商品を販売しない方針を定めた。リスト1に5000元未満の商品を除き、販売価格のみを出力する

list1 = [[ 2000,  550,  2550],[ 3400,  850,  4250],[54000, 15000, 69000]]
for i in list1:
    if i[2] > 5000:
        print(i[2])

1-5)紅商会は新年を迎えるため、5000元以下の商品を販売しない方針を決めた。リスト1から5000ウォン未満の商品をリスト1から除外し、販売中の販売価格のみを出力する。

list1 = [[ 2000,  550,  2550],[ 3400,  850,  4250],[54000, 15000, 69000]]
for i in list1:
    if i[2] < 5000:
        list1.remove(i)
    else:
        print(i[2])

2)フォリル・ウィリアムズの「happy」の歌詞を活用する。かっこ()は「」で、スペースはありません。エンティティのエスケープ文字列部分を表す文字列はスペースに変更され、stringという変数名に保存されます。(繰り返し不要)

happy = '''It might seem crazy what I am 'bout to say
Sunshine she's here, you can take a break
I'm a hot air balloon that could go to space
With the air, like I don't care, baby by the way
Huh (Because I'm happy)
Clap along if you feel like a room without a roof
(Because I'm happy)
Clap along if you feel like happiness is the truth
(Because I'm happy)
Clap along if you know what happiness is to you
(Because I'm happy)
Clap along if you feel like that's what you wanna do
Here come bad news talking this and that (Yeah)
Well give me all you got, don't hold back (Yeah)
Well I should probably warn you I'll be just fine (Yeah)
No offence to you don't waste your time
Here's why
Clap along if you feel like a room without a roof
(Because I'm happy)
Clap along if you feel like happiness is the truth
(Because I'm happy)
Clap along if you know what happiness is to you
(Because I'm happy)
Clap along if you feel like that's what you wanna do
Uh, bring me down
Can't nothing, bring me down
My level's too high to bring me down
Can't nothing, bring me down, I said
Bring me down, can't nothing
Bring me down
My level's too high to bring me down
Can't nothing, bring me down, I said
Clap along if you feel like a room without a roof
(Because I'm happy)
Clap along if you feel like happiness is the truth
(Because I'm happy)
Clap along if you know what happiness is to you
(Because I'm happy)
Clap along if you feel like that's what you wanna do
Clap along if you feel like a room without a roof
(Because I'm happy)
Clap along if you feel like happiness is the truth
(Because I'm happy)
Clap along if you know what happiness is to you
(Because I'm happy)
Clap along if you feel like that's what you wanna do
Uh, bring me down (Happy, happy, happy, happy)
Can't nothing (Happy, happy, happy, happy)
Bring me down, my level's too high
To bring me down (Happy, happy, happy, happy)
Can't nothing (Happy, happy, happy, happy)
Bring me down, I said
Clap along if you feel like a room without a roof
(Because I'm happy)
Clap along if you feel like happiness is the truth
(Because I'm happy)
Clap along if you know what happiness is to you (ayy, ayy, ayy)
(Because I'm happy)
Clap along if you feel like that's what you wanna do
Clap along if you feel like a room without a roof
(Because I'm happy)
Clap along if you feel like happiness is the truth
(Because I'm happy)
Clap along if you know what happiness is to you (hey)
(Because I'm happy)
Clap along if you feel like that's what you wanna do
Come on'''
happy = happy.replace('(', '')
happy = happy.replace(")", '')
string = happy.replace("\n", ' ')
print(string)

2-2)文字列の歌詞単語をスペース単位で切り離し、happy 1というリストに保存する。

happy1 = string.split(' ')
print(happy1)

2-3)フォリル・ウィリアムズの曲Happyはいったい何回収録されるのでしょうか。

string.lower()
happy1 = string.split(' ')
print(happy1.count('happy')) #23번 나온다.

3)str 1を外し、逆さまに印刷します。

str1 = "엔코아 플레이 데이터 인공지능 부트캠프"
str2 = str1.replace(" ", "")[::-1]
print(str2)   #프캠트부능지공인터이데이레플아코엔

1.文字列


1)文字列関数


split(カット)、replace(置換の検索)、strip(小文字の置換)、find/index(検索)、count(文字数単位)、join(マージ)、lower(小文字の置換)、upper(大文字の置換)、isupper(n番目の文字が大文字であるか否かを判断)

  • 変数.split(「区切り文字」、分割回数)
  • 変数.replace(検索、置換、回数は省略可能)
  • 変数.strip(検索して削除する)
  • 文字列の前後白空間をすべてクリアします.
    (補足)
  • 文字列の末尾に新しい行(補足)があるかどうか
  • 不要な文字はすべてクリアできます.
  • 文字列の間のスペースは削除されません.
  • 変数.find(「文字検索」、開始インデックス、終了インデックス)
  • 変数.count(「ユニット文字」)
  • 「区切り文字」.join(変数)リストを区切り文字に分割し、文字列
  • に変換する
  • 変数.低(変数)小文字
  • 変数.upper(変数)大文字
  • 変数[n].isupper()nビット文字は大文字ですか、
  • ですか.
    str1 = '안녕 나는 짱구 아빠야!?!?!?!?!'
    str2 = '안녕/나는/짱구/아빠야/너는/누구니!!!!!'
    
    #split(t, n) t=가를기준 n=가를횟수
    print(str1.split()) #공백이면 한칸 띄어쓰기 
    print(str2.split('/'))
    print(str2.split('/', 3)) #3번째까지 적용
    print(str2.split('/', maxsplit=3)) #최대 3번까지 적용
    print(str2.split('/', 4))  #4번째까지 적용
    
    #변수.replace(찾을것, 바꿀것, 횟수_생략가능)
    print(str1.replace('짱구', '짱아'))
    
    #변수.strip(찾아서제거할것)
    print(str1.strip("!")) 
    
    # 변수.find('찾을 문자', 시작인덱스, 끝인덱스)
    str1.find('짱')
    # 변수.count()
    str1.count('!')
    # '구분자'.join(변수)
    str2_j = '/'.join(str2) # str2.split('/')와 정반대이다.
    
    str3 = 'I am Kim Rocki'
    # 변수.lower() / 변수.upper() 대/소문자로 변환
    print(str3.lower()) #소문자로 바꾸기
    print(str3.upper()) #대문자로 바꾸기
    
    #첫글자를 대문자로 바꾸기
    str3 = str3.split()
    for i in str3:
        i.capitalize()
    str3 = ' '.join(str3)
    print(str3)
    
    #변수[n].isupper()
    print(str3[5].isupper()) #True

    find深化(候補虫)


    大量のデータの間に対応する文字列を見つける必要があります.最初に見つけてくれれば役に立ちますか?
    import re 
    # 정규식 관련된 함수들이 모여있는 모듈
            
    for letter in re.finditer('core', data1):
        print(letter.start(), letter.end()) # start() 시작위치 반환, end() 끝 위치 반환

    2)文字列表現


    A.三種類の表現

    #방법1
    print("저는 {}을 좋아하며 역시 {}도 좋아합니다.".format("방탄소년단", "보라색"))
    print("저는 {1}을 좋아하며 역시 {0}도 좋아합니다.".format("보라색", "방탄소년단"))    #순서바꾸기
    
    age = 31
    artist = "BTS"
    color = "보라색"
    print("저는 {0}살이며 {1}을 좋아하며 역시 {2}도 좋아합니다.".format(age, artist, color)) #변수로 넣기
    
    #방법2
    age = 31
    artist = "BTS"
    color = "보라색"
    print(f"저는 {age}살이며 {artist}을 좋아하며 역시 {color}도 좋아합니다.") #변수를 넣고 싶은 곳에 {}로 구멍을 내서 그 안에 넣고 싶은 변수를 넣는다."")하면 된다
    
    #방법3
    print("저는 %s살 입니다" % 20) #%s는 문자로 모두 출력 가능
    print("저는 %d살, 정확히 %f이며 %c가입니다" % (20, 20.554555, "김")) 
    #d는 정수, f는 실수, c는 하나의 문자로 표현 가능
    
    # 소수점 자릿수 표현(버림) %.nf  n번째 자리까지 출력
    print("저는 %d살, 정확히 %.2f이며 %c가입니다" % (20, 20.554555, "김")) 

    B.ソート

  • :>n右揃えn個のスペース
  • :^nはn個のスペースで中央に
  • 並べられている
    a = 1.1234536346542334125346634
    b = 2
    add = '글자'
    print('The sum of {0} + {1} = {2}'.format(a, b, add))
    print('The sum of {0} + {1:>30} = {2:>10}'.format(a, b, add))
    The sum of 1.1234536346542334 + 2 = 글자
    The sum of 1.1234536346542334 +                           
       2 =         글자

    2.標準出力


    1)印刷の原型


    リファレンス
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    print("Hello", "Python", "Bye")

    A. sep=''

    print("Hello", "Python", "Bye", sep='▶') #sep 기본은 공백(띄어쓰기)이다.

    B. end=''

    print("Hello", "Python", "Bye", sep='▶', end='★')
    #파일을 만들고 그 파일에 쓰는 법

    2). ファイルI/O


    A.データごとに書き込む


    a.テキストデータ
    w:書き込みモード、r:読み出しモード、a:付加モード
    b.バイナリデータ
    wb:書き込みモード、rb:読み取りモード、ab:付加モード

    B.インデックスファイルの書き込み、追加、読み取り

    #새 파일 생성하며 내용 쓰기
    score_file = open("score.txt", "w", encoding="utf8") #열 파일명, write 쓸 목적, utf8한글파일사용시
    print("수학: 0", file=score_file)
    print("영어: 50", file=score_file)
    score_file.close() #파일을 열었다면 닫아줘야한다
    
    #기존 파일에 덧붙여쓸 때
    score_file = open("score.txt", "a", encoding="utf8") #a는 파일에 덧붙여 쓸 때이다.append
    score_file.write("과학: 80")
    score_file.write("\n코딩: 100")
    score_file.close()
    
    #파일을 읽어오기 read, 줄별로 읽기(+줄바꿈 안하고), while 활용, for 활용
    score_file = open("score.txt", "r", encoding="utf8")
    print(score_file.read())
    score_file.close()
    #줄바꿔오며 읽어오기
    score_file = open("score.txt", "r", encoding="utf8")
    print(score_file.readline(), end="")
    print(score_file.readline(), end="")
    print(score_file.readline(), end="")
    print(score_file.readline(), end="")
    score_file.close()

    実験1 While文を用いた逐行出力

    score_file = open("score.txt", "r", encoding="utf8")
    while True:
        line = score_file.readline()
        if not line:
            break
        print(line, end="")
    score_file.close()

    練習2 for文を使用して行単位で出力

    score_file = open("score.txt", "r", encoding="utf8")
    lines = score_file.readlines()
    for line in lines:
        print(line, end="")
    score_file.close()

    B 1と利用率


    文内で解決できます.
    with open("study.txt", "w", encoding="utf8") as study_file:
        study_file.write("코딩을 열심히 하고 있습니다.")
    with open("study.txt", "r", encoding="utf8") as study_file:
        print(study_file.read())

    実験3~50週間のレポートファイルを作成するプログラムを作成します。


    ファイルの内容
  • x毎週レポート-
    部門:
    名前:
    業務概要:
  • for i in range(1, 51):
        with open(str(i)+ "주차.txt", "w", encoding="utf8") as parking_file:
            parking_file.write("- {0}주차 주간보고 - \n부서: \n 이름: \n업무 요약: ".format(i))

    C.バイナリデータの書き込み、読み出し(後ほど補足)

    import pickle
    profile_file = open("profile.pickle", "wb") # w가 아니라 wb이다. 
    profile = {"이름":"박명수", "나이":"31", "취미":["축구", "코딩"]}
    print(profile)
    
    #profile에 있는 정보를 profile_file에 저장
    pickle.dump(profile, profile_file) 
    profile_file.close()
    
    #불러오기
    profile_file = open("profile.pickle", "rb")
    profile = pickle.load(profile_file)
    print(profile)
    profile_file.close()

    3) flush=False


    つまり、ストリームオブジェクトに変換して出力しています.
    #기본 한번에 출력된다.
    import time 
    for i in range(15):
        print(i, flush=False)
        time.sleep(2)
        
    #True일 때는 하나하나 한다.
    import time 
    for i in range(15):
        print(i, flush=True)
        time.sleep(2)