본문 바로가기
IT World/Python

Python Training Day1, Day2. String Formatting, Basic String Operations

by 닷라인웨이 2022. 12. 13.

Python 매일 훈련하기 Reset.

며칠간 파이썬 문제를 매일 풀겠다는 다짐을 지키지 못했다. 밀린 것을 몰아서 다 해치우고 지속하겠다는 것은 습관을 만들기에 비효율적인 방법이다. (자수성가 사업가가 알려준 내용이다.)

그래서 다시 리셋하고 Day 1부터 다시 카운팅 시작하기로 했다.

퇴근하고 집에와서 저녁 먹고 파이썬을 1문제씩 풀고 블로그에 정리까지 하는 게 해 보니까 매일 지속하기 어려운 행위라는 것을 체감하고 방법을 바꿨다. 출근하는 시간은 사람이 너무 많아서 불가능하고, 회사에서 화장실 갔다 오는 왕복 걸음 하는 동안 폰으로 보고, 점심 먹는 동안도 보고, 집에 오는 길에도 사람이 너무 많아서 불가한 정도인데 사람이 많아 2호선 2~3대 보내며 줄 서서 기다리는 동안 봤다. 그 결과, 어제오늘 Python 훈련 진도를 나갈 수 있었다.

(출퇴근 시간 2시간 30분을 반으로만 줄여도 편하게 공부할 시간이 생길텐데 이건 앞으로 해결해야 할 숙제이다.)


 

Chapter 4. String Formatting (learnpython.org)

 

C-style string formatting

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

 

To use two or more argument specifiers, use a tuple (parentheses).

Any object which is not a string can be formatted using the %s operator as well.

 

Basic argument specifiers

%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)

 

문자로 치환하기 위해 %s를 사용했고, 53.44라는 소수점 숫자로 치환하기 위해 %.2f를 넣었는데 맞지 않다고 나와서 %s로 넣었더니 정답이 되었다. (이 부분은 운영 기관에 추후 이메일을 보내던지 해서 물어봐야겠다.)

 

 

Chapter 5. Basic String Operations (learnpython.org)

astring = "Hello world!"
print(astring.index("o"))

That prints out 4, because the location of the first occurrence of the letter "o" is 4 characters away from the first character.

(Python (and most other programming languages) start things at 0 instead of 1. So the index of "o" is 4.)

 

astring = "Hello world!"
print(astring.count("l"))

This counts the number of l's in the string.

 

astring = "Hello world!"
print(astring[3:7])

If you just have one number in the brackets, it will give you the single character at that index. If you leave out the first number but keep the colon, it will give you a slice from the start to the number you left in. If you leave out the second number, it will give you a slice from the first number to the end. You can even put negative numbers inside the brackets. They are an easy way of starting at the end of the string instead of the beginning.

 

astring = "Hello world!"
print(astring[3:7:2])

This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The general form is [start:stop:step].

 

astring = "Hello world!"
print(astring[::-1])

There is no function like strrev in C to reverse a string. But with the above mentioned type of slice syntax you can easily reverse a string like this.

 

astring = "Hello world!"

# These make a new string with all letters converted to uppercase and lowercase, respectively.
print(astring.upper())
print(astring.lower())

# This is used to determine whether the string starts with something or ends with something, respectively.
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))

# This splits the string into a bunch of strings grouped together in a list.
afewwords = astring.split(" ")

 

s = "Hey there! what should this string be?"
# ⓐ Length should be 20
print("Length of s = %d" % len(s))

# ⓑ First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))

# ⓕ Number of a's should be 2
print("a occurs %d times" % s.count("a"))

# ⓖ Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end

# ⓗ Convert everything to uppercase
print("String in uppercase: %s" % s.upper())

# ⓘ Convert everything to lowercase
print("String in lowercase: %s" % s.lower())

# ⓒ Check how a string starts
if s.startswith("Str"):
    print("String starts with 'Str'. Good!")

# ⓓ Check how a string ends
if s.endswith("ome!"):
    print("String ends with 'ome!'. Good!")

# ⓔ Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))

코드를 보고 s라는 변수에 정의된 String의 구성을 변경하는 문제이다. 저기 나열된 코드가 모두 정답을 찾을 수 있는 힌트는 아니고, 정답 유추에 직접적으로 사용할 수 있는 코드를 해석해보면 Strxx a ome!, Strxxxxxxxxxxxxxxxxx 이렇게 문장 구조를 만들 수 있다. 일단 ⓐ~ⓓ까지가 직접적인 힌트이고, ⓕ는 간접적인 힌트이다. ⓖ~ⓘ는 그냥 출력했을 때 보여지는 결과물이다. 이렇게 모든 코드를 다 봐도 정답이 딱 나오지가 않는 문제이다.

정답은 Strings are awesome! 이란다. (a가 두 개라는 힌트만 보고 are awesome을 맞출 수 있는 사람이 얼마나 있을까)

 

 

내일도 Python Training을 계속해야지!

댓글