Hàm Len không dùng trực tiếp trên chuỗi mà phải thông qua 1 biến
Ví dụ :
strings_list = ["một", "hai", "ba"]
length_of_strings = len(strings_list)
print(length_of_strings)
=> =3
Hoặc:
multiple_strings = "một" + "hai" + "ba"
total_length = len(multiple_strings)
print(total_length)
=9
Ví dụ cụ thế:
common_words = ("the", "of", "and", "a", "to","in", "is", "you", "that", "it", "he","was", "for", "on", "are", "as", "with", "his","they", "I", "at", "be", "this", "have", "from")
title = "A - Number of words"
print("\n" + title + "\n" + "-" * len(title))
print(len(common_words))
=25
" \n" + title: Thêm một dòng mới và sau đó là tiêu đề.
"-" * len(title): Tạo một chuỗi gồm các dấu gạch ngang (-) có chiều dài bằng chiều dài của tiêu đề.
"\n": Thêm một dòng mới sau chuỗi dấu gạch ngang.
# show the first 5 words
title = "B - First 5 words"
print("\n" + title + "\n" + "-" * len(title))
print(common_words[:5]) =>print(common_words[:5]): In ra 5 từ đầu tiên trong chuỗi common_words bằng cách sử dụng cú pháp cắt chuỗi ([:5]).
# the last 3 words
title = "C - Last 3 words"
print("\n" + title + "\n" + "-" * len(title))
print(common_words[-3:])
# every fifth word
title = "D - Every 5th word"
print("\n" + title + "\n" + "-" * len(title))
print(common_words[::5])
# iterate over words, listing out the ones with four letters
title = "E - Four-letter words"
print("\n" + title + "\n" + "-" * len(title))
for word in common_words:
# for each word, if it's length is 4 characters, print it
if len(word) == 4:
print(word)
title = "F - Words starting with W"
print("\n" + title + "\n" + "-" * len(title))
for each_word in common_words: =Duyệt qua từng từ trong common_words.
if each_word.lower().startswith("w"): Kiểm tra nếu từ (chuyển đổi thành chữ thường) bắt đầu bằng "w", thì in ra từ đó.
each_word.lower(): Chuyển đổi từ hiện tại thành chữ thường để so sánh không phân biệt chữ hoa chữ thường.
.startswith("w"): Kiểm tra xem từ đó có bắt đầu bằng "w" hay không.
print(each_word)
# show the words in alphabetical order (need to convert to a list first)
title = "G - Words in order"
print("\n" + title + "\n" + "-" * len(title))
list_words = list(common_words)
list_words.sort()
Chuyển đổi tuple
common_words
thành một danh sáchlist_words
.list_words.sort()
: Sắp xếp danh sáchlist_words
theo thứ tự bảng chữ cái.
print(list_words)
Nhận xét
Đăng nhận xét