Introducing Python(연습문제) - 05. 텍스트 문자열

2024. 4. 16. 18:56· - Programming/Python

Q1. m으로 시작하는 단어를 대문자로 만들어보자.

song = 
"""
When an eel grabs your arm,
And it causes great harm,
That's - a money!
"""

A :  줄단위로 분리, 단어단위로 분리, 첫단어가 m인 애들만 M으로 변환 출력

split() : 매개변수값을 기준으로 문자열을 리스트로 분리

capitalize(): 해당 문자열의 첫글자는 대문자로, 그외는 모두 소문자로

rstrip() : 문자열 오른쪽 맨 마지막인덱스 데이터 제거.

song = 
"""
When an eel grabs your arm,
And it causes great harm,
That's - a money!
"""

new_song = ""
for line in song.split("\n"):
  for word in line.split():
    if word[0] == "m":
      new_song += word.capitalize()
    else:
      new_song += word
    new_song += " "
  new_song.rstrip() # 마지막 공백 제거
  new_song += "\n"
new_song.rstrip() # 마지막 줄바꿈 제거
print(new_song)
"""
When an eel grabs your arm, 
And it causes great harm, 
That's - a Money! 
"""

Q2.  다음과 같은 형식으로 각 리스트의 질문과 답을 차례로 출력해보자.

Q: question
A: answer

question = [
"We don't serve strings around here. Are you a string?",
"What is said on Father's Day in the forest?,
"What makes the sound 'Sis! Boom! Bah!'?",
]

answer = [
"An exploding sheep.",
"No, I'm a frayed knot.",
"'Pop!' goes the weasel."
]

A : 

question = [
"We don't serve strings around here. Are you a string?",
"What is said on Father's Day in the forest?",
"What makes the sound 'Sis! Boom! Bah!'?",
]
answer = [
"An exploding sheep.",
"No, I'm a frayed knot.",
"'Pop!' goes the weasel."
]

for i in range(len(question)):
  print(f"Q: {question[i]}")
  print(f"A: {answer[i]}")
"""
Q: We don't serve strings around here. Are you a string?
A: An exploding sheep.
Q: What is said on Father's Day in the forest?
A: No, I'm a frayed knot.
Q: What makes the sound 'Sis! Boom! Bah!'?
A: 'Pop!' goes the weasel.
"""

Q3. 옛 스타일 포매팅을 사용하여 시를 써보자. 문자열 'roat beef', 'ham', 'head', 'clam'을 아래 문자열에 대체한다.

My kitty cat likes %s,
My kitty cat likes %s,
My kitty cat fell on his %s And now thinks he's a %s

A : 

list = ['roat beef', 'ham', 'head', 'clam']

line1 = "My kitty cat likes %s," % list[0]
line2 = "My kitty cat likes %s," % list[1]
line3 = "My kitty cat fell on his %s And now thinks he's a %s" % (list[2], list[3])

print(line1 + "\n" + line2 + "\n" + line3)
"""
My kitty cat likes roat beef,
My kitty cat likes ham,
My kitty cat fell on his head And now thinks he's a clam
"""

Q4. 새 스타일의 포매팅을 사용하여 메일을 써보자. 다음 문자열을 letter 변수에 저장한다.

(다음 문제에서 이 변수를 사용한다)

Dear {salutation} {name},

Thank you for your letter. We are sorry that our {product} {verbed} in your {room}. 
Please note that it should never be used in a {room}, especially near any {animals}.

Send us your receipt and {amount} for shipping and handling. We will send you another {product}
that, in our tests, is {percent}% less likely to have {verbed}.

Thank you for your support.
Sincerely,
{spokesman}
{job_title}

A : 

salutation = "salutation"
name = "name"
product = "product"
verbed = "verbed"
room = "room"
animals = "animals"
amount = "amount"
percent = "percent"
spokesman = "spokesman"
job_title = "job_title"

letter = f"""
Dear {salutation} {name},

Thank you for your letter. We are sorry that our {product} {verbed} in your {room}. 
Please note that it should never be used in a {room}, especially near any {animals}.

Send us your receipt and {amount} for shipping and handling. We will send you another {product}
that, in our tests, is {percent}% less likely to have {verbed}.

Thank you for your support.
Sincerely,
{spokesman}
{job_title}
"""

print(letter)
"""
Dear salutation name,

Thank you for your letter. We are sorry that our product verbed in your room. 
Please note that it should never be used in a room, especially near any animals.

Send us your receipt and amount for shipping and handling. We will send you another product
that, in our tests, is percent% less likely to have verbed.

Thank you for your support.
Sincerely,
spokesman
job_title
"""

Q5. 문자열 변수 'salutation', 'name', 'product', 'verbed', 'room', 'animals', 'amount', 'percent', 'spokesman', 'job_title'에

값을 할당한다. 문자열 변수와 letter.format()를 사용하여 메일을 출력해보자.

A : 

list = ['salutation', 'name', 'product', 'verbed', 'room', 'animals', 'amount', 'percent', 'spokesman', 'job_title']

letter = f"""
Dear {list[0]} {list[1]},

Thank you for your letter. We are sorry that our {list[2]} {list[3]} in your {list[4]}. 
Please note that it should never be used in a {list[4]}, especially near any {list[5]}.

Send us your receipt and {list[6]} for shipping and handling. We will send you another {list[2]}
that, in our tests, is {list[7]}% less likely to have {list[3]}.

Thank you for your support.
Sincerely,
{list[8]}
{list[9]}
"""

print(letter)
"""
Dear salutation name,

Thank you for your letter. We are sorry that our product verbed in your room. 
Please note that it should never be used in a room, especially near any animals.

Send us your receipt and amount for shipping and handling. We will send you another product
that, in our tests, is percent% less likely to have verbed.

Thank you for your support.
Sincerely,
spokesman
job_title
"""

Q6. 어떤 물건에 이름을 짓는 여론 조사를 실시한 후 다음과 같은 패턴이 나타났다.

- an English submarine 이름은 (Boaty McBoatface)로 지어졌다.
- an Australian racehorse 이름은 (Horsey McHorseface)로 지어졌다.
- a Swedish train 이름은 (Trainy McTrainface)로 지어졌다.

문자열 'duck', 'gourd', spitz'과 % 포매팅을 사용하여 위 괄호안에 밑줄 문자열의 형식과 같이 출력해보자.

[출력]
Ducky McDuckface
Gourdy McGourdface
Spitzy McSpitzface

A : 

print("%sy Mc%sface" % ("Duck", "Duck"))
print("%sy Mc%sface" % ("Gourd", "Gourd"))
print("%sy Mc%sface" % ("Spitz", "Spitz"))

Q7. format() 메서드를 사용하여 문제 [Q6]을 풀어본다.

A :

print("{0}y Mc{1}face".format("Duck", "Duck"))
print("{0}y Mc{1}face".format("Gourd", "Gourd"))
print("{0}y Mc{1}face".format("Spitz", "Spitz"))

Q8. f-문자열을 사용하여 [Q6]를 풀어본다.

A : 

name = ["Duck","Gourd","Spitz"]

print(f"{name[0]}y Mc{name[0]}face")
print(f"{name[1]}y Mc{name[1]}face")
print(f"{name[2]}y Mc{name[2]}face")

 

'- Programming/Python' 카테고리의 다른 글
  • Introducing Python(연습문제) - 07. 튜플과 리스트
  • Introducing Python(연습문제) - 06. 반복문: while과 for문
  • Introducing Python(연습문제) - 04. 선택하기:if
  • Introducing Python(연습문제) - 03.숫자
Doo_Nas
Doo_Nas
Doo_Nas
개발자로써 살고 싶은 빵도리
Doo_Nas
----
Let's posting
전체
오늘
어제
  • 전체 글 (22)
    • - CSE (5)
    • - Programming (13)
      • Python (10)
      • C# (3)
      • K8s (0)
      • JavaScript (0)
    • - Coding Test (1)
    • - DB (0)
      • SQL (0)
      • NoSQL (0)
    • - Journal (1)
      • Memoir (1)
    • - Tips (2)

블로그 메뉴

  • 💾 깃허브
  • ❎ 벨로그
  • 📖 방명록
  • 📷 인스타

공지사항

인기 글

태그

  • console
  • process
  • 시행착오
  • dotnet
  • 기초
  • vscode
  • CS
  • Python
  • 세팅
  • 파이썬
  • 오류방지
  • csharp
  • c#
  • 닷넷
  • .NET
  • 부동소수점
  • Framework

최근 댓글

최근 글

hELLO · 정상우.v4.3.0
Doo_Nas
Introducing Python(연습문제) - 05. 텍스트 문자열
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.