【发布时间】:2020-07-16 06:49:22
【问题描述】:
我需要在不使用 Python 内置函数的情况下编写以下函数:
- 如果字符串都是字母字符
- 如果字符串全部大写
- 如果字符串全是数字
- 交换大小写字符
- 将所有字符转换为小写
我已经尝试了一段时间,但想不出太多。 有人有什么提示吗?
【问题讨论】:
标签: function numbers lowercase
我需要在不使用 Python 内置函数的情况下编写以下函数:
我已经尝试了一段时间,但想不出太多。 有人有什么提示吗?
【问题讨论】:
标签: function numbers lowercase
对于其中的大多数,我使用 ASCII 值进行逻辑和转换。
def is_up_case(string):
"""Shows whether or not all characters in a string are uppercase"""
for character in string:
if not (65 <= ord(character) <= 90) and (character != " "): # only allows capital letters and spaces
return False
return True
def is_low_case(string):
"""Shows whether or not all characters in a string are lowercase"""
for character in string:
if not (97 <= ord(character) <= 122) and (character != " "):
return False
return True
def is_alpha(string):
"""Shows whether or not all characters in a string are alphabetical"""
for character in string:
if not (97 <= ord(character) <= 122) and not (65 <= ord(character) <= 90) and (character != " "):
return False
return True
def up_case(string):
"""Converts letters to uppercase"""
new_str = ""
for character in string:
ascii_val = ord(character)
if 97 <= ascii_val <= 122:
ascii_val -= 32 # 32 is the distance between ASCII values of each lowercase and its uppercase companion
new_str += chr(ascii_val)
return new_str
def low_case(string):
"""Converts letters to lowercase"""
new_str = ""
for character in string:
ascii_val = ord(character)
if 65 <= ascii_val <= 90:
ascii_val += 32
new_str += chr(ascii_val)
return new_str
def swap_case(string):
"""Swaps uppercase to lowercase and vice versa"""
new_str = ""
for character in string:
ascii_val = ord(character)
if 65 <= ascii_val <= 90:
ascii_val += 32
elif 97 <= ascii_val <= 122:
ascii_val -= 32
else:
pass
new_str += chr(ascii_val)
return new_str
def is_numbers(string): # I could have used ASCII values with this one too, but I wanted to spice it up ;)
"""Shows if all numbers in a string can be converted to integers"""
try:
int(string)
return True
except ValueError: # if it fails to convert the whole statement into integers, it will return False
return False # spaces will also cause it to return as False
希望这会有所帮助!
【讨论】: