Как отобразить специальные символы в Python с печатью
В программе Python, которую я пишу, мне нужно напечатать символ (авторское право). Есть простой способ сделать это? Или это не поддерживается в Python? Вот пример.
print ("\(copyright symbol here\)")
В качестве примечания: вы действительно хотите эти обратные слеши там? Если это так, лучше либо явно удвоить их, либо использовать необработанную строку, чем полагаться на тот факт, что \( и \) не являются escape-последовательностями.
Хм . Использование только одной обратной косой черты всегда помогало мне печатать кавычки и скобки. Спасибо за совет, хотя.
5 ответов
В Python вы можете поместить символы Unicode внутри строк тремя способами. (Если вы используете 2.x вместо 3.x, проще использовать строку Юникода — как в u»…» вместо «…» — и вам нужно использовать unichr вместо chr , но в противном случае все одно и то же.)
- »: Введите его напрямую.
- Это означает, что вам, вероятно, придется выбрать кодировку символов для исходного кода, например, явно сохранить файл как UTF-8 и поместить заголовок кодировки вверху. (Для 3.3 UTF-8 по умолчанию, поэтому вам не нужен заголовок кодировки, если это то, что вы используете.)
- В Mac OS X, при настройке клавиатуры на большинстве языков, это опция -G.
- В Windows я полагаю, что вы можете использовать трюк с цифровой клавиатурой с 0169, чтобы войти в него, хотя это не кажется очень легким.
- Если вы не знаете, как набирать «» на клавиатуре, скопируйте и вставьте его из другого места ( «знак авторского права» Google, и вы должны найти страницу, которую вы можете скопировать, или, если на то пошло, право отсюда).
- Или у вашего компьютера, вероятно, есть средство просмотра символов или что-то подобное, что позволяет указывать и нажимать специальные символы.
- Google для «знака авторского права Unicode», и вы быстро увидите, что он U + 00A9. В Python это «\u00a9 ‘.
- Для чего-либо, кроме Basic Multilingual Plane, то есть более четырех шестнадцатеричных цифр, используйте капитал U и 8 цифр.
- Опять же, вам, вероятно, понадобится google, чтобы найти правильное имя для объекта.
- Это не полностью документировано, какие имена вы можете использовать и не можете использовать. Но он обычно работает, когда вы ожидаете его, и COPYRIGHT SIGN , очевидно, более читабельна, чем 00a9 .
Вы также можете делать вещи косвенно — например, unicodedata.lookup(‘COPYRIGHT SIGN’) или chr(0xa9) вернет ту же строку, что и литералы выше. Но на самом деле нет причин не использовать литерал.
Unicode HOWTO в документах Python имеет намного больше подробностей об этом — если вы не хотите читать все это, Тип строки описывает различные типы escape-последовательностей (и проблемы с кодированием/декодированием между строками unicode и байтов, что особенно важно в 2.x ) и Unicode Literals в исходном коде Python описывает, как указать объявление кодирования.
Если вы хотите использовать официальный список всех персонажей, которые вы можете использовать, а не просто искать по ним, просмотрите unicodedata docs для ваша версия Python, которая содержит ссылки на соответствующую версию базы данных символов Unicode. (Например, это 6.1.0 в 3.3.0, 5.2.0 в 2.7.3 и т.д.). Вам нужно будет перемещаться по нескольким ссылкам, чтобы попасть в фактический список, но это единственный способ, которым вы будете получить что-то, что гарантируется точно, что скомпилировано в Python. (И, если вас это не волнует, вы можете просто просто поиграть в Google или использовать Википедию или просмотрщик персонажей на компьютере.)
Python Special characters
The characters which have some unique functionality, such characters are called special characters.
List of Python special/escape characters:
- \n — Newline
- \t- Horizontal tab
- \r- Carriage return
- \b- Backspace
- \f- Form feed
- \’- Single Quote
- \»- double quote
- \\-Backslash
- \v -vertical tab
- \N — N is the number for Unicode character
- \NNN — NNN is digits for Octal value
- \xNN — NN is a hex value; \x is used to denote following is a hex value.
- \a — bell sound, actually default chime
>>> print("chercher\ntech") chercher tech >>> print("chercher\ttech") chercher tech >>> print("This is\" symbol") This is" symbol >>> print('This is \' symbol') This is ' symbol >>> print("This is\\ symbol") This is\ symbol >>> print("Chercher\rTech") Techcher >>> print("CherCher\bTech") CherCheTech >>> print("CherCher\fTech") CherCher♀Tech >>> print("\110\151") Hi >>> print("\x48\x69") Hi >>>
How to check if a string contains any special characters
Import the re to match the string using regular expression.
The search function matches each character present inside the test_string string with the special characters present in the regular expression.
If there is a match it returns the character that matched otherwise it returns None. Based on the result, structure your logic.
import re string_check= re.compile('[@_!#$%^&*()<>?/\|><~:]') test_string /cdn-cgi/l/email-protection" data-cfemail="4d2e25283f2e25283f0d39282e25">[email protected]" if(string_check.search(test_string) == None): print("Contains NO Special Characters.") else: print("Contains Special Characters.") print(string_check.search(test_string)) #print the special chars
Contains Special Characters.
You can check whether a string starts with a special character.
test_string = "$chercher@$tech" print(test_string.startswith("$")) #Output True
How to print special characters in Python
Sometimes we might want to print the special characters to see special characters present in the string. For example, printing special characters in normal way prints the Str\ting as Str ing because we have «\t» in the string.
To print the special characters as it is, we have to use repr() functions.
base_string = "Str\ting" special_string = repr(base_string) print("base string: "+ base_string) print("special_string :"+special_string)
The output of printing special characters
base string: Str ing special_string :'Str\ting'
Python Comments
Python comments are those who start with the hash(#) character and extended to the end of the physical line, where the python virtual machine does not execute the line with the hash character, A comment may appear at the start of the line or following by the whitespace but never come in between the string.
For multiline comments, you can use the hash character at the beginning of every line.
# print("chercher.tech software solutions") print("This is an example of comment in python")
So if you observe, in the above image, the line with the hash character has not printed in the output as it is ignored by the python virtual machine.
Multi-line comment in Python
Another way to comment on multiple lines in python is by using triple quotes. The string literal when not assigned to a variable is completely ignored by the python interpreter. Three consecutive single »’ or double » » « quotes can be placed before and after the text for long comments in the code.
''' This is a multiple line comment in python ''' " " " The comments are completely ignored by python interpreter " " "
Python Constants
In Python, the constants are usually declared and assigned on a module, and a module means the new file containing a variable and functions which is imported to the main file.
Constants are written in uppercase and separated by the underscore, and this constant concept is not really implemented in python.
The Kitchin Research Group
Printing unicode characters in Python strings
Posted February 02, 2014 at 12:18 PM | categories: python, unicode | tags:
Are you tired of printing strings like this:
print 'The volume is Angstrom^3'.format(125)
The volume is 125 Angstrom^3
Wish you could get Å in your string? That is the unicode character U+212B. We can get that to print in Python, but we have to create it in a unicode string, and print the string properly encoded. Let us try it out.
We use u» to indicate a unicode string. Note we have to encode the string to print it, or will get this error:
Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u212b' in position 0: ordinal not in range(128)
Do more, do more, we wish we could! Unicode also supports some superscripted and subscripted numbers (http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts ). Let us see that in action.
print u'\u212B\u00B3'.encode('utf-8')
Pretty sweet. The code is not all that readable if you aren’t fluent in unicode, but if it was buried in some library it would just print something nice looking. We can use this to print chemical formulas too.
print u'''The chemical formula of water is H\u2082O. Water dissociates into H\u207A and OH\u207B'''.encode('utf-8')
=The chemical formula of water is H₂O. Water dissociates into H⁺ and OH⁻
There are other encodings too. See the symbols here: http://en.wikipedia.org/wiki/Number_Forms
print u'1/4 or \u00BC'.encode('latin-1')
print u'A good idea\u00AE'.encode('latin-1')
I can not tell how you know exactly what encoding to use. If you use utf-8 in the example above, you get a stray character in front of the desired trademark symbol. Still, it is interesting you can get prettier symbols!
Copyright (C) 2014 by John Kitchin. See the License for information about copying.