Lệnh dấu cách trong python
Bất kỳ ký tự nào nằm trong cặp dấu nháy đơn hoặc nháy kép điều là một String (một chuỗi ký tự). Có nhiều phương thức xử lý chuỗi khác nhau. Để kiểm tra độ dài của một chuỗi, ta sử dụng phương thức len(). Show Nội dung chính
letter = 'P' # Chuỗi có thể là một ký tự đơn lẻ hoặc một loạt các ký tự print(letter) # P print(len(letter)) # 1 greeting = 'Hello, World!' # String could be a single or double quote,"Hello, World!" print(greeting) # Hello, World! print(len(greeting)) # 13 sentence = "I hope you are enjoying days of Python Challenge" print(sentence) Tạo chuỗiĐể tạo một chuỗi gồm nhiều dòng ta sử dung 3 dấu nháy đơn hoặc 3 dấu nháy kép. Hãy xem ví dụ sau: # cách 1 multiline_string = '''I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created days of python.''' print(multiline_string) # cách 2 multiline_string = """I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created days of python.""" print(multiline_string) Nối chuỗiChúng ta có thể nối các chuỗi lại với nhau. Xem ví dụ bên dưới: first_name = 'Leonel' last_name = 'Messi' space = ' ' full_name = first_name + space + last_name print(full_name) # Leonel Messi # Kiểm tra độ dài của chuỗi print(len(first_name)) # 6 print(len(last_name)) # 5 print(len(first_name) > len(last_name)) # True print(len(full_name)) # 12 Escape SequenceTrong python hoặc các ngôn ngữ lập trình khác, theo sau dấu \ là một ký tự.
print('I hope everyone is enjoying the Python Challenge.\nAre you ?') print('Days\tTopics\tExercises') print('Day 1\t3\t5') print('Day 2\t3\t5') print('Day 3\t3\t5') print('Day 4\t3\t5') print('This is a backslash symbol (\\)') print('In every programming language it starts with \"Hello, World!\"') # output I hope every one is enjoying the Python Challenge. Are you ? Days Topics Exercises Day 1 5 5 Day 2 6 20 Day 3 5 23 Day 4 1 35 This is a backslash symbol (\) In every programming language it starts with "Hello, World!" Định dạng% OperatorTrong python có rất nhiều cách tạo chuỗi. Trong phần này, ta sẽ đề cập đến một số trong số chúng. Toán tử % được sử dụng để định dạng một tập hợp các biến nằm trong một tuple (danh sách có kích thước cố định), cùng với một chuỗi định dạng, chứa văn bản bình thường cùng với "mã chỉ định đối số", các ký hiệu đặc biệt như "%s" , "%d", "%f", "%.f".
# Strings first_name = 'Leonel' last_name = 'Messi' language = 'Python' formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language) print(formated_string) # I am Leonel Messi. I teach Python # Strings và Numbers radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) print(formated_string) #The area of circle with a radius 10 is 314.00. python_libraries = ['Django', 'Flask', 'Numpy', 'Pandas'] formated_string = 'The following are python libraries:%s' % (python_libraries) print(formated_string) # "The following are python libraries:['Django', 'Flask', 'Numpy', 'Pandas']" str.formatĐịnh dạng này được giới thiệu trong phiên bản python 3. first_name = 'Leonel' last_name = 'Messi' language = 'Python' formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language) print(formated_string) # I am Leonel Messi. I teach Python a = 4 b = 3 print('{} + {} = {}'.format(a, b, a + b)) print('{} - {} = {}'.format(a, b, a - b)) print('{} * {} = {}'.format(a, b, a * b)) print('{} / {} = {:.2f}'.format(a, b, a / b)) # limits it to two digits after decimal print('{} % {} = {}'.format(a, b, a % b)) print('{} // {} = {}'.format(a, b, a // b)) print('{} ** {} = {}'.format(a, b, a ** b)) # output 4 + 3 = 7 4 - 3 = 1 4 * 3 = 12 4 / 3 = 1.33 4 % 3 = 1 4 // 3 = 1 4 ** 3 = 64 # Strings and numbers radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of a cricle with a radius {} is {:.2f}.'.format(radius, area) print(formated_string) #The area of a cricle with a radius 10 is 314.00. f-Strings (Python 3.6+)Một dạng chuỗi mới khác là nội suy chuỗi, f-string. Các chuỗi bắt đầu bằng f và chúng ta có thể đưa dữ liệu vào các vị trí tương ứng của chúng. a = 4 b = 3 print(f'{a} + {b} = {a +b}') # 4 + 3 = 7 print(f'{a} - {b} = {a - b}') # 4 - 3 = 1 print(f'{a} * {b} = {a * b}') # 4 * 3 = 12 print(f'{a} / {b} = {a / b:.2f}')# 4 / 3 = 1.33 print(f'{a} % {b} = {a % b}') # 4 % 3 = 1 print(f'{a} // {b} = {a // b}') # 4 // 3 = 1 print(f'{a} ** {b} = {a ** b}') # 4 ** 3 = 64 Ký tự trong chuỗi
language = 'Python' a,b,c,d,e,f = language print(a) # P print(b) # y print(c) # t print(d) # h print(e) # o print(f) # n
language = 'Python' first_letter = language[0] print(first_letter) # P second_letter = language[1] print(second_letter) # y last_index = len(language) - 1 last_letter = language[last_index] print(last_letter) # n Nếu chúng ta muốn lấy các ký tự bắt đầu từ bên phải thì chúng ta có thể sử dụng cách sau: language = 'Python' last_letter = language[-1] print(last_letter) # n second_last = language[-2] print(second_last) # o Cắt chuỗiTrong python, chúng ta có thể cắt một chuỗi mẹ thành nhiều chuỗi con. language = 'Python' first_three = language[0:3] # Bắt đầu từ chỉ mục 0 và lên đến 3 nhưng không bao gồm 3 last_three = language[3:6] print(last_three) # hon # Cách khác last_three = language[-3:] print(last_three) # hon last_three = language[3:] print(last_three) # hon Bỏ qua các ký tựCó thể bỏ qua các ký tự trong khi cắt bằng cách chuyển đối số bước cho phương thức cắt. language = 'Python' pto = language[0,6:2] print(pto) # Pto Đảo ngược một chuỗiChúng ta có thể dễ dàng đảo ngược các ký tự trong chuỗi trong python bằng cách sau: greeting = 'Hello, World!' print(greeting[::-1]) # !dlroW ,olleH Các phương thức khácTrong ngôn ngữ lập trình Python, có nhiều phương thức xử lý chuỗi cho phép chúng ta định dạng chuỗi (ta có thể sử dụng dir() để xem các phương thức). Hãy xem một số phương thức xử lý chuỗi trong các ví dụ sau:
challenge = 'thirty days of python' print(challenge.capitalize()) # 'Thirty days of python'
challenge = 'thirty days of python' print(challenge.count('y')) # 3 print(challenge.count('y', 7, 14)) # 1 print(challenge.count('th')) # 2
challenge = 'thirty days of python' print(challenge.endswith('on')) # True print(challenge.endswith('tion')) # False
challenge = 'thirty\tdays\tof\tpython' print(challenge.expandtabs()) # thirty days of python print(challenge.expandtabs(10)) # thirty days of python
challenge = 'thirty days of python' print(challenge.find('y')) # 5 print(challenge.find('th')) # 0 print(challenge.find('thong')) # -1
challenge = 'thirty days of python' print(challenge.find('y')) # 5 print(challenge.find('th')) # 1 print(challenge.find('thong')) # -1
first_name = 'Leonel' last_name = 'Messi' job = 'teacher' country = 'Argentina' sentence = 'I am {} {}. I am a {}. I live in {}.'.format(first_name, last_name, job, country) print(sentence) # I am Leonel Messi. I am a teacher. I live in Argentina. radius = 10 pi = 3.14 area = pi * radius ** 2 result = 'The area of a circle with radius {} is {}'.format(str(radius), str(area)) print(result) # The area of a circle with radius 10 is 314.0
challenge = 'thirty days of python' sub_string = 'da' print(challenge.index(sub_string)) # 7 print(challenge.index(sub_string, 9)) # error
challenge = 'thirty days of python' sub_string = 'da' print(challenge.rindex(sub_string)) # 8 print(challenge.rindex(sub_string, 9)) # error
challenge = 'ThirtyDaysPython' print(challenge.isalnum()) # True challenge = '30DaysPython' print(challenge.isalnum()) # True challenge = 'thirty days of python' print(challenge.isalnum()) # False, khoảng trắng không phải là ký tự chữ và số challenge = 'thirty days of python 2019' print(challenge.isalnum()) # False
challenge = 'thirty days of python' print(challenge.isalpha()) # False, khoảng trắng không thuộc nhóm ký tự az AZ challenge = 'ThirtyDaysPython' print(challenge.isalpha()) # True num = '123' print(num.isalpha()) # False
challenge = 'thirty days of python' print(challenge.isdecimal()) # False challenge = '123' print(challenge.isdecimal()) # True challenge = '\u00B2' print(challenge.isdigit()) # False challenge = '12 3' print(challenge.isdecimal()) # False, không được phép khoản trắng
challenge = 'Thirty' print(challenge.isdigit()) # False challenge = '30' print(challenge.isdigit()) # True challenge = '\u00B2' # ² print(challenge.isdigit()) # True
num = '10' print(num.isnumeric()) # True num = '\u00BD' # ½ print(num.isnumeric()) # True num = '10.5' print(num.isnumeric()) # False
challenge = '30DaysOfPython' print(challenge.isidentifier()) # False, Bởi vì bắt đầu bằng một con số challenge = 'thirty_days_of_python' print(challenge.isidentifier()) # True
challenge = 'thirty days of python' print(challenge.islower()) # True challenge = 'Thirty days of python' print(challenge.islower()) # False
challenge = 'thirty days of python' print(challenge.isupper()) # False challenge = 'THIRTY DAYS OF PYTHON' print(challenge.isupper()) # True
web_tech = ['HTML', 'CSS', 'JavaScript', 'React'] result = '# '.join(web_tech) print(result) # HTML# CSS# JavaScript# React
challenge = 'thirty days of pythoonnn' print(challenge.strip('noth')) # irty days of py
challenge = 'thirty days of python' print(challenge.replace('python', 'coding')) # thirty days of codings
challenge = 'thirty days of python' print(challenge.split()) # ['thirty', 'days', 'of', 'python'] challenge = 'thirty, days, of, python' print(challenge.split(', ')) # ['thirty', 'days', 'of', 'python']
challenge = 'thirty days of python' print(challenge.swapcase()) # THIRTY DAYS OF PYTHON challenge = 'Thirty Days Of Python' print(challenge.swapcase()) # tHIRTY dAYS oF pYTHON
challenge = 'thirty days of python' print(challenge.startswith('thirty')) # True challenge = '30 days of python' print(challenge.startswith('thirty')) # False Bài tập
|