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

Đếm chữ hoa/chữ thường không dùng hàm tích hợp Python

Bài toán: cho chuỗi, đếm số ký tự hoa và thường không dùng hàm tích hợp (isupper, islower).

Giải pháp: dùng mã ASCII qua hàm ord(). Chữ thường: 97-122 (a-z), chữ hoa: 65-90 (A-Z).

Ví dụ

def upperlower(string):
    upper = 0
    lower = 0
    for i in range(len(string)):
        # Chữ thường: ASCII 97-122
        if ord(string[i]) >= 97 and ord(string[i]) <= 122:
            lower += 1
        # Chữ hoa: ASCII 65-90
        elif ord(string[i]) >= 65 and ord(string[i]) <= 90:
            upper += 1
    print('Lower case characters = ' + str(lower))
    print('Upper case characters = ' + str(upper))

string = 'TutorialsPoint'
upperlower(string)

Kết quả:

Lower case characters = 12
Upper case characters = 2

Đếm chữ hoa/chữ thường không dùng hàm tích hợp Python

Kết luận

Đã học đếm chữ hoa/thường bằng mã ASCII (ord) thay vì isupper/islower.