Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo viết tắt (Acronym) trong Python

Cho chuỗi s đại diện cụm từ, tạo viết tắt: lấy chữ cái đầu mỗi từ (trừ "and"), viết hoa.

Ví dụ: "Indian Space Research Organisation" → "ISRO".

Các bước giải quyết

  • tokens = s.split()
  • string = ""
  • Với mỗi word trong tokens: nếu word != "and" thì string += word[0]
  • Trả về string.upper()

Ví dụ mã Python

class Solution:
    def solve(self, s):
        tokens = s.split()
        string = ""
        for word in tokens:
            if word != "and":
                string += str(word[0])
        return string.upper()

ob = Solution()
print(ob.solve("Indian Space Research Organisation"))

Đầu vào

"Indian Space Research Organisation"

Đầu ra

ISRO