- Кирилица в Python
- Ответы (3 шт):
- How to Make a List of the Alphabet in Python
- Using the string Module to Make a Python List of the Alphabet
- Using Map to Make a Python List of the Alphabet
- Conclusion
- Additional Resources
- Русский алфавит через char
- Решение
- How to Make a List of the Alphabet in Python
- Using the string Module to Make a Python List of the Alphabet
- Using Map to Make a Python List of the Alphabet
- Conclusion
- Additional Resources
Кирилица в Python
Есть ли в python аналог для string.ascii_letters , только для кириллицы?
>>> import string >>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>>
Ответы (3 шт):
Не думаю, что для кириллицы это есть.
vowels = 'аоиеёэыуюя' consonants = 'бвгджзйклмнпрстфхцчшщьъ' cyrillic_lower_letters = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' cyrillic_upper_letters = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' cyrillic_letters = cyrillic_lower_letters + cyrillic_upper_letters
Зная, что код кириллических символов в таблице unicode идёт от 1040 до 1103, где сначала заглавные, а затем строчные, мы можем сделать так:
cyrillic_lower = [(lambda c: chr(c))(i) for i in range(1072, 1104)] cyrillic_upper = [(lambda c: chr(c))(i) for i in range(1040, 1072)] cyrillic_ansi = cyrillic_lower + cyrillic_upper
И получим следующий список: [‘а’, ‘б’, ‘в’, ‘г’, ‘д’, ‘е’, ‘ж’, ‘з’, ‘и’, ‘й’, ‘к’, ‘л’, ‘м’, ‘н’, ‘о’, ‘п’, ‘р’, ‘с’, ‘т’, ‘у’, ‘ф’, ‘х’, ‘ц’, ‘ч’, ‘ш’, ‘щ’, ‘ъ’, ‘ы’, ‘ь’, ‘э’, ‘ю’, ‘я’, ‘А’, ‘Б’, ‘В’, ‘Г’, ‘Д’, ‘Е’, ‘Ж’, ‘З’, ‘И’, ‘Й’, ‘К’, ‘Л’, ‘М’, ‘Н’, ‘О’, ‘П’, ‘Р’, ‘С’, ‘Т’, ‘У’, ‘Ф’, ‘Х’, ‘Ц’, ‘Ч’, ‘Ш’, ‘Щ’, ‘Ъ’, ‘Ы’, ‘Ь’, ‘Э’, ‘Ю’, ‘Я’]
Если нужно получить именно строку, то вот:
cyrillic_ansi_str = ''.join(cyrillic_ansi)
и соответствующий результат: ‘абвгдежзийклмнопрстуфхцчшщъыьэюяАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ’
Ну тогда и я свой вариант добавлю, если порядок следования букв не очень важен:
cyrillic_letters = ''.join(map(chr, range(ord('А'), ord('я')+1))) + 'Ёё' # 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяЁё'
Будет работать в любой кодировке, где русские буквы идут в таблице подряд, начиная с А и заканчивая я . Правда, с Ёё отдельный прикол, но они обычно везде как-то отдельно лежат.
How to Make a List of the Alphabet in Python
In this tutorial, you’ll learn how to use Python to make a list of the entire alphabet. This can be quite useful when you’re working on interview assignments or in programming competitions. You’ll learn how to use the string module in order to generate a list of either and both the entire lower and upper case of the ASCII alphabet. You’ll also learn some naive implementations that rely on the ord() and chr() functions.
Using the string Module to Make a Python List of the Alphabet
The simplest and, perhaps, most intuitive way to generate a list of all the characters in the alphabet is by using the string module. The string module is part of the standard Python library, meaning you don’t need to install anything. The easiest way to load a list of all the letters of the alphabet is to use the string.ascii_letters , string.ascii_lowercase , and string.ascii_uppercase instances.
As the names describe, these instances return the lower and upper cases alphabets, the lower case alphabet, and the upper case alphabet, respectively. The values are fixed and aren’t locale-dependent, meaning that they return the same values, regardless of the locale that you set.
Let’s take a look at how we can load the lower case alphabet in Python using the string module:
# Loading the lowercase alphabet to a list import string alphabet = list(string.ascii_lowercase) print(alphabet) # Returns: ['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', 'z']
Let’s break down how this works:
- We import the string module
- We then instantiate a new variable, alphabet , which uses the string.ascii_lowercase instance.
- This returns a single string containing all the letters of the alphabet
- We then pass this into the list() function, which converts each letter into a single string in the list
The table below shows the types of lists you can generate using the three methods:
We can see that we evaluate an expression for each item in an iterable. In order to do this, we can iterate over the range object between 97 and 122 to generate a list of the alphabet. Let’s give this a shot!
# Generate a list of the alphabet in Python with a list comprehensions alphabet = [chr(value) for value in range(97, 123)] print(alphabet) # Returns: ['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', 'z']
While our for loop wasn’t very complicated, converting it into a list comprehension makes it significantly easier to read! We can also convert our more dynamic version into a list comprehension, as show below:
# Generate a list of the alphabet in Python with a list comprehension alphabet = [chr(value) for value in range(ord('a'), ord('a') + 26)] print(alphabet) # Returns: ['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', 'z']
In the final section, you’ll learn how to use the map() function to generate a list of the alphabet in Python.
Using Map to Make a Python List of the Alphabet
In this section, you’ll make use of the map() function in order to generate the alphabet. The map function applies a function to each item in an iterable. Because of this, we can map the chr function to each item in the range covering the letters of the alphabet. The benefit of this approach is increased readability by being able to indicate simply what action is being taken on each item in an iterable.
Let’s see what this code looks like:
# Generate a list of the alphabet in Python with map and chr alphabet = list(map(chr, range(97, 123))) print(alphabet) # Returns: ['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', 'z']
Here, we use the map() function and pass in the chr function to be mapped to each item in the range() covering 97 through 123. Because the map() function returns a map object, we need to convert it to a list by using the list() function.
Conclusion
In this tutorial, you learned a number of ways to make a list of the alphabet in Python. You learned how to use instances from the string module, which covers lowercase and uppercase characters. You also learned how to make use of the chr() and ord() functions to convert between Unicode and integer values. You learned how to use these functions in conjunction with a for loop, a list comprehension, and the map() function.
Additional Resources
To learn more about related topics, check out the articles listed below:
Русский алфавит через char
Русский алфавит
Нужно создать программу так чтобы переводила каждую букву Русского алфавита в цифру + 2 А 1+2=.
Русский алфавит в массив
Как бы так задать массив русского алфавита, но не вручную вводить каждую букву.
Строки, русский алфавит
Задание: Дана последовательность слов русского языка, между словами – запятая, за последним словом.
Строки и русский алфавит
удалите это, пожалуйста Случайно не в тот раздел написал. Извините
Сообщение было отмечено Rottbauer как решение
Решение
Добавлено через 3 минуты
Логично, что как-то так. Только учитывайте, что кодировка у «Ё» не соответствует правилу.
Строки и русский алфавит
В проге считываешь с файла строку на кириллице. Например: "ололо", длину выведет 10. Почему? А как.
Множества. Русский алфавит
Здравствуйте. Дан текст на русском языке. Напечатать в алфавитном порядке все согласные буквы.
AnsiString и русский алфавит
Здравствуйте, возник вопрос по AnsiString такого рода : дана строка AnsiString, как получить.
Множества. Русский алфавит
дан текст на русском языке. Напечатать в алфавитном порядке все звонкие согласные буквы, которые.
Вывести русский алфавит
Вывожу английский алфавит через Chr(i+97) без проблем, а вот русский не получается i+224. Что не.
Вывести в консоли русский алфавит
программа должна вывести в консоли русский алфавит, после чего если нажать цифру 1, то выскочит.
How to Make a List of the Alphabet in Python
In this tutorial, you’ll learn how to use Python to make a list of the entire alphabet. This can be quite useful when you’re working on interview assignments or in programming competitions. You’ll learn how to use the string module in order to generate a list of either and both the entire lower and upper case of the ASCII alphabet. You’ll also learn some naive implementations that rely on the ord() and chr() functions.
Using the string Module to Make a Python List of the Alphabet
The simplest and, perhaps, most intuitive way to generate a list of all the characters in the alphabet is by using the string module. The string module is part of the standard Python library, meaning you don’t need to install anything. The easiest way to load a list of all the letters of the alphabet is to use the string.ascii_letters , string.ascii_lowercase , and string.ascii_uppercase instances.
As the names describe, these instances return the lower and upper cases alphabets, the lower case alphabet, and the upper case alphabet, respectively. The values are fixed and aren’t locale-dependent, meaning that they return the same values, regardless of the locale that you set.
Let’s take a look at how we can load the lower case alphabet in Python using the string module:
# Loading the lowercase alphabet to a list import string alphabet = list(string.ascii_lowercase) print(alphabet) # Returns: ['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', 'z']
Let’s break down how this works:
- We import the string module
- We then instantiate a new variable, alphabet , which uses the string.ascii_lowercase instance.
- This returns a single string containing all the letters of the alphabet
- We then pass this into the list() function, which converts each letter into a single string in the list
The table below shows the types of lists you can generate using the three methods:
We can see that we evaluate an expression for each item in an iterable. In order to do this, we can iterate over the range object between 97 and 122 to generate a list of the alphabet. Let’s give this a shot!
# Generate a list of the alphabet in Python with a list comprehensions alphabet = [chr(value) for value in range(97, 123)] print(alphabet) # Returns: ['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', 'z']
While our for loop wasn’t very complicated, converting it into a list comprehension makes it significantly easier to read! We can also convert our more dynamic version into a list comprehension, as show below:
# Generate a list of the alphabet in Python with a list comprehension alphabet = [chr(value) for value in range(ord('a'), ord('a') + 26)] print(alphabet) # Returns: ['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', 'z']
In the final section, you’ll learn how to use the map() function to generate a list of the alphabet in Python.
Using Map to Make a Python List of the Alphabet
In this section, you’ll make use of the map() function in order to generate the alphabet. The map function applies a function to each item in an iterable. Because of this, we can map the chr function to each item in the range covering the letters of the alphabet. The benefit of this approach is increased readability by being able to indicate simply what action is being taken on each item in an iterable.
Let’s see what this code looks like:
# Generate a list of the alphabet in Python with map and chr alphabet = list(map(chr, range(97, 123))) print(alphabet) # Returns: ['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', 'z']
Here, we use the map() function and pass in the chr function to be mapped to each item in the range() covering 97 through 123. Because the map() function returns a map object, we need to convert it to a list by using the list() function.
Conclusion
In this tutorial, you learned a number of ways to make a list of the alphabet in Python. You learned how to use instances from the string module, which covers lowercase and uppercase characters. You also learned how to make use of the chr() and ord() functions to convert between Unicode and integer values. You learned how to use these functions in conjunction with a for loop, a list comprehension, and the map() function.
Additional Resources
To learn more about related topics, check out the articles listed below: