https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py
def upper(word: str) -> str:
"""
Will convert the entire string to uppercase letters
>>> upper("wow")
'WOW'
>>> upper("Hello")
'HELLO'
>>> upper("WHAT")
'WHAT'
>>> upper("wh[]32")
'WH[]32'
"""
# converting to ascii value int value and checking to see if char is a lower letter
# if it is a capital letter it is getting shift by 32 which makes it a capital case letter
return "".join(
chr(ord(char) - 32) if 97 <= ord(char) <= 122 else char for char in word
)
if __name__ == "__main__":
from doctest import testmod
testmod()
https://github.com/TheAlgorithms/Python/blob/master/strings/lower.py
def lower(word: str) -> str:
"""
Will convert the entire string to lowecase letters
>>> lower("wow")
'wow'
>>> lower("HellZo")
'hellzo'
>>> lower("WHAT")
'what'
>>> lower("wh[]32")
'wh[]32'
>>> lower("whAT")
'what'
"""
# converting to ascii value int value and checking to see if char is a capital letter
# if it is a capital letter it is getting shift by 32 which makes it a lower case letter
return "".join(
chr(ord(char) + 32) if 65 <= ord(char) <= 90 else char for char in word
)
if __name__ == "__main__":
from doctest import testmod
testmod()
转载https://www.cnblogs.com/sui776265233/p/9103251.html
ord()函数主要用来返回对应字符的ascii码,chr()主要用来表示ascii码对应的字符他的输入时数字,可以用十进制,也可以用十六进制。
例如:
print ord('a)
#97
print chr(97)
#a
print chr(0x61)
#a
下面的例子实现对字符串str1里面所有的字符,转换成ascii码中比他们小一位的字符。
str1='asdfasdf123123'
for i in rang(len(str1)):
print (chr(ord(str1[i])-1))
可以用来生成随机验证码(由大写字母和数字构成):
import random
# 1X3Y3ZX
def make_code(size=7):
res = ''
for i in range(size):
# 循环一次则得到一个随机字符(字母/数字)
s = chr(random.randint(65, 90))
num = str(random.randint(0, 9))
res += random.choice([s, num])
return res
res=make_code()
print(res)
网友评论