我如何迭代通过字母表?

  1. 在 Python 中,我可以简单地 + + 一个 char 吗?
  2. What is an efficient way of doing this?

我想循环遍历 URL 并以下面的方式生成它们:

www.website.com/term/#
www.website.com/term/a
www.website.com/term/b
www.website.com/term/c
www.website.com/term/d ...
www.website.com/term/z
140040 次浏览

您可以使用 string.ascii_lowercase,它只是一个方便的小写字母字符串,

Python 2示例:

from string import ascii_lowercase


for c in ascii_lowercase:
# append to your url

Python 3示例:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from string import ascii_lowercase as alc
for i in alc:
print(f"www.website.com/term/{i}")


# Result
# www.website.com/term/a
# www.website.com/term/b
# www.website.com/term/c
# ...
# www.website.com/term/x
# www.website.com/term/y
# www.website.com/term/z

或者,如果你想继续筑巢,你可以这样做:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
for i in alc:
print(f"www.website.com/term/{i}")
for j in alc:
print(f"www.website.com/term/{i}{j}")


# Result
# www.website.com/term/a
# www.website.com/term/aa
# www.website.com/term/ab
# www.website.com/term/ac
# ...
# www.website.com/term/ax
# www.website.com/term/ay
# www.website.com/term/az
# www.website.com/term/b
# www.website.com/term/ba
# www.website.com/term/bb
# www.website.com/term/bc
# ...
# www.website.com/term/bx
# www.website.com/term/by
# www.website.com/term/bz
# www.website.com/term/c
# www.website.com/term/ca
# www.website.com/term/cb
# www.website.com/term/cc
# ...
# ...
# ...
# www.website.com/term/z
# www.website.com/term/za
# www.website.com/term/zb
# www.website.com/term/zc
# www.website.com/term/zd
# ...
# www.website.com/term/zx
# www.website.com/term/zy
# www.website.com/term/zz

除了 string.ascii_lowercase,您还应该看看 ordchr内置的。ord('a')将给出 'a'的 ascii 值,而 chr(ord('a'))将返回字符串 'a'

使用这些,您可以通过字符代码增加和减少,并转换来回足够容易。ASCII table也是一个很好的书签。

最短的路

for c in list(map(chr,range(ord('a'),ord('z')+1))):
do_something(base_url+c)

迭代函数

def plusplus(oldChar):
return chr(ord(oldChar)+1)
plusplus('a') # output - b

Another option

url=www.website.com/term
my_char=ord('a') # convert char to ascii
while my_char<= ord('z'):
my_char+=1 # iterate over abc
my_url=url+chr(my_char)  # convert ascii to char
do_something(my_url)

基于@Brian 的回答。