ascii码到数字,数字到ascii码的转换:
print ord('a) #97
print chr(97) #a
print chr(0x61) #a
给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
- 全部字母都是大写,比如"USA"。
- 单词中所有字母都不是大写,比如"leetcode"。
- 如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。
否则,我们定义这个单词没有正确使用大写字母。
示例 1:
输入: "USA"
输出: True
示例 2:
输入: "FlaG"
输出: False
注意: 输入是由大写和小写拉丁字母组成的非空单词。
补充ascii对应的数字:
ord()将字符转换为ASCII码
# 要求:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
def count(s):
count_a=count_z=count_o=count_s=0
for i in s:
if (ord(i)>=97 and ord(i)<=122) or (ord(i)>=65 and ord(i)<=90):
count_a=count_a+1
elif ord(i)>=48 and ord(i)<=57:
count_z=count_z+1
elif ord(i)==32:
count_s=count_s+1
else:
count_o=count_o+1
print "英文字母个数:%d个"%count_a
print "数字个数:%d个"%count_z
print "其他字符个数:%d个"%count_o
print "空格个数:%d个"%count_s
if __name__=="__main__":
s=raw_input("请输入一串字符:")
count(s)
解答:
# -*- coding:utf-8 -*-
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
count_b = 0
for i in word:
if(ord(i)>=65 and ord(i)<=90): # 如果是大写字母
count_b+=1
if(count_b==len(word) or count_b==0): # 全是小写或者全是大写
return True
if(count_b==1 and ord(word[0])>=65 and ord(word[0])<=90): # 如果只有第一个字母是大写
return True
else:
return False
def main():
word = "a"
rs = Solution()
print(rs.detectCapitalUse(word))
if __name__ == '__main__':
main()
class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
t = word
t1 = word.upper()
t2 = word.lower()
t3 = t2.title() #首字母大写
return t==t1 or t==t2 or t==t3