- Python strings with special characters
- # Table of Contents
- # Print a string with the special characters in Python
- # Print a string with the special characters using encode() and decode()
- # Print a string with the special characters using a raw string
- # Print a backslash in Python
- # Print a backslash using a raw string
- Escape Sequences in Python
- Raw strings
- Common escape sequences
- Python Special characters
- How to check if a string contains any special characters
- How to print special characters in Python
- Python Comments
- Python Constants
Python strings with special characters
Last updated: Feb 21, 2023
Reading time · 4 min
# Table of Contents
# Print a string with the special characters in Python
Use the repr() function to print a string with the special characters, e.g. print(repr(my_str)) .
The repr() function returns a string containing a printable representation of the provided object.
Copied!my_str = 'bobby\nhadz\ncom\n' print(repr(my_str)) # 👉️ 'bobby\nhadz\ncom\n'
We used the repr() function to print a string with the special characters.
The repr() function returns a printable representation of the provided object rather than the string itself.
# Print a string with the special characters using encode() and decode()
Alternatively, you can use the str.encode() and bytes.decode() methods to convert the string to a raw string before printing.
Copied!my_str = 'bobby\nhadz\ncom\n' result = my_str.encode('unicode_escape') print(result) # 👉️ b'bobby\\nhadz\\ncom\\n' result = my_str.encode('unicode_escape').decode() print(result) # 👉️ bobby\nhadz\ncom\n
The str.encode method returns an encoded version of the string as a bytes object.
We used the unicode_escape encoding to escape the special characters with an extra backslash.
The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8 .
Encoding is the process of converting a string to a bytes object and decoding is the process of converting a bytes object to a string .
# Print a string with the special characters using a raw string
If you have access to the variable’s declaration, you can prefix the string with r to mark it as a raw string.
Copied!my_str = r'bobby\nhadz\ncom\n' print(my_str) # 👉️ bobby\nhadz\ncom\n
If you need to use variables in the raw string, use a formatted string literal.
Copied!variable = 'hadz' my_str = fr'bobby\nvariable>\ncom\n' print(my_str) # 👉️ bobby\nhadz\ncom\n
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Make sure to wrap expressions in curly braces — .
Notice that we prefixed the string with fr and not just with f or r .
The start of an expression in an f-string is marked using curly braces.
If you need to include the literal characters in the string, use two sets of curly braces.
Copied!variable = 'hadz' my_str = fr'>>bobby\nvariable>\ncom\n' print(my_str) # 👉️ >bobby\nhadz\ncom\n
# Print a backslash in Python
If you need to print a backslash:
- Use a second backslash character to escape each backslash in the string.
- Use the print() function to print the result.
Copied!my_str = 'Bobby\\Hadz\\Com' print(my_str) # 👉️ Bobby\Hadz\Com
The example uses a second backslash to escape each backslash character in the string.
The backslash \ character has a special meaning in Python — it is used as an escape character (e.g. \n or \t ).
By adding a second backslash, we treat the \ as a literal character.
Copied!my_str = 'Bobby\\Hadz\\Com' print(my_str) # 👉️ Bobby\Hadz\Com
If you need to print two backslash characters next to one another, use four backslashes.
Copied!my_str = 'Bobby\\\\Hadz\\\\Com' print(my_str) # 👉️ Bobby\\Hadz\\Com
# Print a backslash using a raw string
Alternatively, you can use a raw string.
When a string is prefixed with r , it treats backslashes as literal characters and escaping them is not necessary.
Copied!my_str = r'Bobby\Hadz\Com' print(my_str) # 👉️ Bobby\Hadz\Com my_str = r'Bobby\\Hadz\\Com' print(my_str) # 👉️ Bobby\\Hadz\\Com
Escape Sequences in Python
Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.
For example, imagine you initialized a string with single quotes:
But if you include an apostrophe without escaping it, then you will get an error:
File "main.py", line 1 s = 'Hey, what's up?' ^ SyntaxError: invalid syntax
To fix this, just escape the apostrophe:
To add newlines to your string, use \n :
print("Multiline strings\ncan be created\nusing escape sequences.")
Multiline strings can be created using escape sequences.
An important thing to remember is that, if you want to include a backslash character in a string, you will need to escape that. For example, if you want to print a directory path in Windows, you’ll need to escape each backslash in the string:
Raw strings
A raw string can be used by prefixing the string with r or R , which allows for backslashes to be included without the need to escape them. For example:
print(r"Backslashes \ don't need to be escaped in raw strings.")
Backslashes \ don't need to be escaped in raw strings.
But keep in mind that unescaped backslashes at the end of a raw string will cause and error:
print(r"There's an unescaped backslash at the end of this string\")
File "main.py", line 1 print(r"There's an unescaped backslash at the end of this string\") ^ SyntaxError: EOL while scanning string literal
Common escape sequences
Escape Sequence | Meaning |
---|---|
\ | Backslash ( \ ) |
‘ | Single quote ( ‘ ) |
« | Double quote ( » ) |
\n | ASCII Linefeed (adds newline) |
\b | ASCII Backspace |
A full list of escape sequences can be found here in the Python docs.
If this article was helpful, tweet it .
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
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="dcbfb4b9aebfb4b9ae9ca8b9bfb4">[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.