以下是一个示例代码,用于遍历字符串并打印字符之间的距离:
def print_distance(string):
current_index = 0
for i in range(len(string)-1):
current_char = string[i]
next_char = string[i+1]
distance = ord(next_char) - ord(current_char)
print(f"The distance between '{current_char}' and '{next_char}' is {distance}")
current_index += 1
# 示例用法
input_string = "abcde"
print_distance(input_string)
运行上述代码将输出:
The distance between 'a' and 'b' is 1
The distance between 'b' and 'c' is 1
The distance between 'c' and 'd' is 1
The distance between 'd' and 'e' is 1
这段代码遍历了给定的字符串,并计算了每对相邻字符之间的距离。距离是通过将字符转换为其ASCII码值,并计算差值来计算的。在每次迭代中,它会打印出每对字符和它们之间的距离。
上一篇:遍历字符串并查找整数?