社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

包括范围循环Python 3中的最后一个值

jake84 • 3 年前 • 1153 次点击  

当我运行循环时,我在试图让代码打印范围的最后一个值时遇到问题。下面是我在最后的代码中遇到的问题:

start_character = "A"
end_character = "Z"

#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.

#Print all the letters from start_character to end_character,
#each on their own line. Include start_character and
#end_character themselves.
#
#Remember, you can convert a letter to its underlying ASCII
#number using the ord() function. ord("A") would give 65.
#ord("Z") would give 90. You can use these values to write
#your loop.
#
#You can also convert an integer into its corresponding ASCII
#character using the chr() function. chr(65) would give "A".
#chr(90) would give "Z". So, for this problem, you'll need
#to convert back and forth between ordinal values and
#characters based on whether you're trying to loop over
#numbers or print letters.
#
#You may assume that both start_character and end_character
#are uppercase letters (although you might find it fun to
#play around and see what happens if you put other characters
#in instead!).


#Add your code here! With the original values for
#start_character and end_character, this will print the
#letters from A to Z, each on their own line.

for char in range(ord(start_character), ord(end_character)):
    for h in chr(char):
        print(h)

以下是我收到的输出:

A B C D E F G H I J K L M N O P Q R S T U V W X Y

我知道我缺少了一些简单的东西,在字符末尾加+1不起作用,因为它不是字符串。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130454
文章 [ 3 ]  |  最新文章 3 年前
Chinnmay B S
Reply   •   1 楼
Chinnmay B S    4 年前

在for循环中使用ord(结束字符)+1

ord(字符):此函数返回整数值(ASCII)加1。

Killian Fortman
Reply   •   2 楼
Killian Fortman    4 年前

在范围循环中,可以将+1添加到结尾字符,如下所示:

for char in range(ord(start_character), ord(end_character) + 1):

python中的ord将字符转换为整数。

grantslape
Reply   •   3 楼
grantslape    4 年前

我想你只需要确定你是在序数上加1,而不是在字符上加1。此外,你不需要内在的 for 循环,只需将当前索引转换回具有 chr() :

for char in range(ord(start_character), ord(end_character)+1):
    print(chr(char))