Python if диапазон символов

Можно ли сделать диапазон букв в Python?

Вы можете использовать ord() для преобразования букв в ординалы символов и обратно:

def char_range(start, end, step=1): for char in range(ord(start), ord(end), step): yield chr(char) 

Кажется, все работает отлично:

>>> ''.join(char_range('a', 'z')) 'abcdefghijklmnopqrstuvwxy' 
import string def letter_range(f,l,al = string.ascii_lowercase): for x in al[al.index(f):al.index(l)]: yield x print ' '.join(letter_range('a','h')) 

Нет встроенного диапазона букв, но вы можете написать один:

def letter_range(start, stop): for c in xrange(ord(start), ord(stop)): yield chr(c) for x in letter_range('a', 'h'): print x, 

мне легче читать хотя бы/понять (и вы можете легко настроить, какие буквы включены и в каком порядке):

letters = 'abcdefghijklmnopqrstuvwxyz' for each in letters: print each result: a b c . z 

. новичок на сайте, как сделать так, чтобы блок кода отображался правильно? (в отличие от того, что я поставил выше?)

Решение Emanuele отлично, если только вы запрашиваете диапазон одиночных символов, что я допущу, это то, что поставил первоначальный вопросник. Существуют также решения для генерации всех многосимвольных комбинаций: Как сгенерировать диапазон строк от aa. до zz. Тем не менее, я подозреваю, что кто-то, кто хочет, чтобы функция типа диапазона, возможно, захотела иметь дело с созданием произвольного диапазона от say ‘y’ до ‘af’ (переключение с ‘z’ на ‘aa’). Итак, вот более общее решение, которое включает в себя возможность либо указать последний элемент диапазона, либо его длину.

def strange(start, end_or_len, sequence='ABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Create a generator of a range of 'sequential' strings from start to end_or_len if end_or_len is a string or containing end_or_len entries if end_or_len is an integer. >>> list(strange('D', 'F')) ['D', 'E', 'F'] >>> list(strange('Y', 'AB')) ['Y', 'Z', 'AA', 'AB'] >>> list(strange('Y', 4)) ['Y', 'Z', 'AA', 'AB'] >>> list(strange('A', 'BAA', sequence='AB')) ['A', 'B', 'AA', 'AB', 'BA', 'BB', 'AAA', 'AAB', 'ABA', 'ABB', 'BAA'] >>> list(strange('A', 11, sequence='AB')) ['A', 'B', 'AA', 'AB', 'BA', 'BB', 'AAA', 'AAB', 'ABA', 'ABB', 'BAA'] """ seq_len = len(sequence) start_int_list = [sequence.find(c) for c in start] if isinstance(end_or_len, int): inclusive = True end_int_list = list(start_int_list) i = len(end_int_list) - 1 end_int_list[i] += end_or_len - 1 while end_int_list[i] >= seq_len: j = end_int_list[i] // seq_len end_int_list[i] = end_int_list[i] % seq_len if i == 0: end_int_list.insert(0, j-1) else: i -= 1 end_int_list[i] += j else: end_int_list = [sequence.find(c) for c in end_or_len] while len(start_int_list) < len(end_int_list) or start_int_list = seq_len: start_int_list[i] = 0 if i == 0: start_int_list.insert(0,0) else: i -= 1 start_int_list[i] += 1 if __name__ =='__main__': import doctest doctest.testmod() 

Источник

Python. Значение в промежутке

Как в питоне узнать, принадлежит ли значение переменной String промежутку из некоторых значений. Ну, пример на Паскале будет выглядеть так: if(s in ['0'..'9']) then. //если s принадлежит множеству <'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'>, то выполнится условие.
Как сделать то же самое, но на Питоне?

если надо задать диапазон символов, можно например таким выражением:
[chr(i) for i in range(ord('a'),ord('z')+1)]

принадлежность символа диапазону соответственно:
'a' in [chr(i) for i in range(ord('a'),ord('z'))]

Читайте также:  Узнать версию python ubuntu

диапазон целых чисел - специальная функция range():
range(2,9)

Ты имел виду, если список содержит некий элемент?

if "31312" in mylist:
print("yes")

В Python строки и символы не различаются, поэтому они не относятся к перечислимым типам. Надо преобразовывать в коды функцией ord. И есть проблема - range не включает правую границу, т. е. '9' не попадает в диапазон. Надо делать
if ord(s) in range(ord('0'),ord('9')+1):
но проще все-таки
if s.isdigit(): # если s - цифра

другими словами, символы в питоне это строки единичной длины, но получить коллекцию из диапазона символов можно: [chr(i) for i in range(ord('a'),ord('z')+1)]и необязательно представлять как множество числовых кодов, ord() дает код символа, дальше функция range создает коллекцию с диапазоном числовых кодов символов, затем она преобразуется этим выражением в коллекцию (список) соответствующих символов (функция chr() дает символ (строку единичной длины с символом) по его коду).

Источник

Python Range of Letters

To produce a range of letters (characters) in Python, you have to write a custom function that:

# Character range function def range_char(start, stop): return (chr(n) for n in range(ord(start), ord(stop) + 1)) # Example run for character in range_char("a", "g"): print(character)

This is the quick answer. Feel free to use this code in your project.

However, to understand how it works, let’s build this function from scratch step by step.

How Does Range of Characters Function Work in Python

Let’s take a look at how the above code works. We are going to build the above function piece by piece by going through the key principles that make it work.

To follow along, you should be an intermediate/advanced Python programmer. For beginners, I recommend skipping the generator part at the end.

The ord() Function in Python

In Python, each Unicode character, such as “a”, “b”, or “c” is an integer under the hood.

For example, here is the Unicode table for the English alphabet.

Unicode Character Unicode Character Unicode Character Unicode Character
64 @ 80 P 96 ` 112 p
65 A 81 Q 97 a 113 q
66 B 82 R 98 b 114 r
67 C 83 S 99 c 115 s
68 D 84 T 100 d 116 t
69 E 85 U 101 e 117 u
70 F 86 V 102 f 118 v
71 G 87 W 103 g 119 w
72 H 88 X 104 h 120 x
73 I 89 Y 105 i 121 y
74 J 90 Z 106 j 122 z
75 K 91 [ 107 k 123
76 L 92 \ 108 l 124 |
77 M 93 ] 109 m 125 >
78 N 94 ^ 110 n 126 ~
79 O 95 _ 111 o

In Python, you can check the integer value of any character using the built-in ord() function.

For instance, let’s check Unicode values for “a”, “b”, and “c”:

ord("a") # 97 ord("b") # 98 ord("c") # 99

As you can see, this returns the same values that are present in the Unicode table above.

The chr() Function in Python

In Python, you can turn (some) integers into characters.

This is natural because as you learned, each character is a number under the hood.

In Python, there is a built-in chr() function. This converts an integer to a corresponding character value.

For instance, let’s turn numbers 110, 111, and 112 into characters:

print(chr(110)) print(chr(111)) print(chr(112))

Now you understand how to convert a character into an integer, and an integer back to a character.

This brings us to a key point related to the range of characters in Python: A range of characters is actually generated using a range of numbers. It is possible only because we know how to convert characters to integers and vice versa.

For example, you can create a range of characters using the built-in range() function and the ord() function:

for number in range(ord("a"), ord("h")): print(number)

If you want to convert these numbers back to characters, call the chr() function on the numeric values:

for number in range(ord("a"), ord("h")): print(chr(number))

Inclusive Range

Now you already have a naive implementation for a range of characters in Python.

But in the above example, the range ends at “g” even though it should end at “h”. This is due to the exclusive nature of the range() function, that is, the last value is not included in the range.

To fix this, add 1 to the end of the range. In other words, extend the range by one to include the “last” value.

For example, let’s create a range of characters from “a” to “h” such that the “h” is included:

for number in range(ord("a"), ord("h") + 1): print(chr(number))

Convert the For Loop into a Function

Now you have a simple for loop that prints characters from “a” to “h”.

But you obviously want to be more general.

Let’s use the logic from the previous example to create a function that returns a range of characters as a list. Instead of hard-coding the strings “a” and “h”, let’s make the function accept general inputs start and stop:

def range_char_list(start, stop): result = [] for number in range(ord(start), ord(stop) + 1): result.append(chr(number)) return result

Now let’s call this function to create a list of characters between “a” and “l”:

a_to_l = range_char_list("a", "l") print(a_to_l)

And there is your naive implementation for the character range function.

Meanwhile, this approach already meets your demand, let’s take it a step further by using generators.

Generator Approach

So far you have implemented an inclusive character range as a function that returns a list of characters.

However, this function stores all the characters into a list in memory. But do we really need to store them?

The characters are independent of one another. That is, the value of “a” does not depend on the value of “b” or any other character in the range.

This means you may use a generator instead of a function to generate the range. In other words, you do not store the entire sequence of characters. Instead, you generate them one at a time with a generator function.

If you are unfamiliar with generators, feel free to check this article.

In short, a generator function does not return values. Instead, it gives you an iterator object that yields values one at a time without storing them. This saves memory when the sequence of items is big in size. The best part of generators is they allow a loop-like syntax. This makes it look as if the generator stored the values even if it does not.

Let’s convert the range of characters function into a generator:

def range_char(start, stop): for number in range(ord(start), ord(stop) + 1): yield(chr(number))

This generator yields the characters one at a time.

As mentioned, you can use this generator in a for loop just like you would do with any other iterable in Python.

for character in range_char("a", "h"): print(character)

Generator Expression

To complete the implementation of the range of characters, let’s make a small final tweak into the function.

Similar to list comprehensions, Python generators support generator comprehensions (known as generator expressions). This allows you to compress the implementation of a generator into a one-liner shorthand.

The general syntax for a generator expression is:

( operate(value) for value in sequence if condition )

This expression is equivalent to calling this generator:

def generate(): for value in sequence: if condition: yield operate(value)

As you can see, you save some lines of code and do not need to use the yield statement at all. Sometimes this can make the code more readable and improve the code quality.

Let’s apply this knowledge to our generator that generates the range of characters.

This turns the existing generator:

def range_char(start, stop): for number in range(ord(start), ord(stop) + 1): yield(chr(number))

Into a shorthand version of it:

def range_char(start, stop): return (chr(n) for n in range(ord(start), ord(stop) + 1))

Do not let the return statement confuse you here. This function still returns an iterator that yields the characters in the range one at a time.

If the generator part sounds Gibberish to you, please familiarize yourself with generators. It takes a while to wrap your head around them.

Also, keep in mind this last part is optional. It is up to a debate whether the shorthand actually improved the code quality or not.

Anyway, this is a necessary step to make the example complete.

Conclusion

Today you learned how to produce a range of letters in Python.

  • You started with a hard-coded range of characters using a for loop.
  • Then you created an inclusive range of characters that includes the last character.
  • Then you wrote a function that returns a range of characters as a list.
  • Finally, you turned this function into a memory-friendly generator.

To recap the idea behind the range of characters in Python:

  • Express characters as integers.
  • Create a range of integers.
  • Convert the range of integers back to characters.

Источник

Оцените статью