-
[Python tutorial] 5. Data type - Strings코딩/Python 2022. 12. 21. 17:11728x90
Strings
Assign String to a Variable
a = "Hello"
파이썬 문자열은 변경 불가
a = 'Python' a[0] = 'J' # error
Multiline Strings
a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" b = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' # """string""", '''string''' 동일
'End of line' 자동 삽입 방지하려면 \ 사용
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
Strings are Arrays
a = "Hello, World!" print(a[1]) # e
Looping Through a String
for x in "banana": print(x)
b
a
n
a
n
aString Length: len()
a = "Hello, World!" print(len(a)) # 13
Check String: keyword
in
문자열이나 문자가 있는지 확인, True/False
txt = "The best things in life are free!" print("free" in txt) # True
txt = "The best things in life are free!" if "free" in txt: # True print("Yes, 'free' is present.")
Check if NOT:
not in
txt = "The best things in life are free!" print("expensive" not in txt) # True
txt = "The best things in life are free!" if "expensive" not in txt: # True print("No, 'expensive' is NOT present.")
Slicing
b = "Hello, World!" # slicing print(b[2:5]) #llo # 5는 제외(2-4 포함), 첫 글자의 인덱스는 0 # Slice From the Start print(b[:5]) # Hello # Slice To the End print(b[2:]) # llo, World! # Negative Indexing print(b[-5:-2]) # orl # -는 0에서 시작하지 않고 -1부터 시작
Modify Strings
a = "Hello, World!" b = " Hello, World! " # Upper Case: upper() print(a.upper()) # HELLO, WORLD! # Lower Case: lower() print(a.lower()) # hello, world! # Remove Whitespace: strip() print(b.strip()) # Hello, World! # Replace String: replace() print(a.replace("H", "J")) # Jello, World! # Split String: split() print(a.split(",")) # ['Hello', ' World!']
String Concatenation
+
a = "Hello" b = "World" c = a + " " + b print(c) # Hello World
*
3* 'un' + 'ium' # 'unununium'
Escape Characters
txt = "We are the so-called \"Vikings\" from the north." print(txt) # We are the so-called "Vikings" from the north.
Code Result ' Single Quote \\ Backslash \n New Line \r Carriage Return \t Tab \b Backspace \f Form Feed \ooo Octal value \xhh Hex value Raw string, r
\등의 특수문자의 이스케이프를 방지
윈도우에서 \ 사용으로 필수, 맥은 / 사용하므로 필수 사용 아님print('C:\some\name') # \n: new line print(r'C:\some\name')
String format: format(), {}
age = 36 txt = "My name is John, and I am {}" print(txt.format(age)) # My name is John, and I am 36
quantity = 3 itemno = 567 price = 49.1 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) # I want 3 pieces of item 567 for 49.1 dollars.
Index number & number format
quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2:.2f} dollars for {0} pieces of item {1}." # index numbers print(myorder.format(quantity, itemno, price)) # I want to pay 49.10 dollars for 3 pieces of item 567.
Named Indexes
myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Ford", model = "Mustang"))
String methods
기타 참고자료
Text Sequence Type — str
String Methods
Formatted string literals
Format String Syntax
printf-style String Formatting728x90'코딩 > Python' 카테고리의 다른 글
[Python tutorial] 7. Data type - List (0) 2022.12.21 [Python tutorial] 6. Data type - Boolean (0) 2022.12.21 [Python tutorial] 4. Data type - Numbers (0) 2022.12.21 [Python tutorial] 3. Data types (0) 2022.12.21 [Python tutorial] 2. Basic, Variables, Module, User input (0) 2022.12.21