How do you print a string with special characters in python?

I would like to display the escape characters when using print statement. E.g.

a = "Hello\tWorld\nHello World"
print a
Hello   World
Hello World

I would like it to display: "Hello\tWorld\nHello\sWorld"

BartoszKP

33.8k13 gold badges103 silver badges128 bronze badges

asked Jun 25, 2011 at 12:50

Use repr:

a = "Hello\tWorld\nHello World"
print[repr[a]]
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print[repr[a].replace[' ',r'\s']]

answered Jun 25, 2011 at 12:52

unutbuunutbu

795k170 gold badges1718 silver badges1620 bronze badges

1

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr[]
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

answered Jun 25, 2011 at 13:28

robertrobert

31.8k8 gold badges52 silver badges72 bronze badges

Not the answer you're looking for? Browse other questions tagged python printing escaping character or ask your own question.

  • Problem Formulation
  • Solution 1: repr[] – Print Without Interpreting Escape Characters
  • Solution 2: Print Raw String to Ignore Special Meaning of Escape Chars
  • Solution 3: Filtering Out All Escape Characters with string.isalnum[]
  • Where to Go From Here?

Problem Formulation

Python has special “escape characters” that start with the single backslash such as \n, \t, and \". If you print a string with escape characters, Python prints the special meaning—for example, a new line for the newline character \n.

s = "Learn\tprogramming\nwith\t\tFinxter!"
print[s]

You can see that the output prints the special meaning of the escape characters:

Learn	programming
with		Finxter!

How to print the string in its original form without interpreting the escape characters?

This is what we want:

s = "Learn\tprogramming\nwith\t\tFinxter!"
print[s]
# Learn\tprogramming\nwith\t\tFinxter!

Solution 1: repr[] – Print Without Interpreting Escape Characters

If you do want to print the escape characters in a string without interpreting them, i.e., skip their special meaning, use the built-in repr[s] function on the string s.

The following example shows how the print output was unaffected by the escape characters—Python prints without the special meaning of the escape characters \t and \n.

s = "Learn\tprogramming\nwith\t\tFinxter!"
print[repr[s]]
# Learn\tprogramming\nwith\t\tFinxter!

Python’s built-in repr[obj] function returns the standard string representation of the provided object. The function internally calls the method obj.__repr__[] which is defined per default for all objects.

You can learn more about the function in my detailed blog article and the following video tutorial:

Python repr[] Function – A Helpful Guide with Example

Solution 2: Print Raw String to Ignore Special Meaning of Escape Chars

Alternatively, you can print a raw string r"..." to print the string without interpreting the escape characters. For example, the statement print['r"Learn\tprogramming\nwith\t'] will simply print the raw string "Learn\tprogramming\nwith\t".

s = r"Learn\tprogramming\nwith\t\tFinxter!"
print[s]
# Learn\tprogramming\nwith\t\tFinxter

This solution is actually the same as the first one because Python internally calls the repr[] function on the raw string.

However, what if you actually want to remove all escape characters from the string output?

Solution 3: Filtering Out All Escape Characters with string.isalnum[]

To clean a string from escape and all other special characters, you can filter out all characters that are not alphanumeric using the string.isalnum[] method like so: ''.join[c for c in s if c.isalnum[]]. This returns a new string that is free from all escape characters.

Let’s have a look at this code snippet that removes the newline and tabular escape characters from the string:

s = 'Learn\tprogramming\nwith\t\tFinxter!'
s_clean = ''.join[c for c in s if c.isalnum[]]
print[s_clean]
# LearnprogrammingwithFinxter

This code makes use of three concepts:

  • The ''.join[] method to glue together all characters in an iterable. Learn more about this method in our detailed blog tutorial.
  • Generator expression to dynamically create an iterable of characters and filter out each non-alphanumeric character. Learn more about this method in our full blog guide.
  • The string.isalnum[] method to check for a given character whether it’s a non-special character. Learn more here.

I suggest you watch the following introduction on generator expression if you don’t feel very confident yet:

Understanding Generators In Python

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do you show special characters in a string?

To display them, Java has created a special code that can be put into a string: \". Whenever this code is encountered in a string, it is replaced with a double quotation mark.

How do you get special characters in Python?

Python Special Characters.
\n - Newline..
\t- Horizontal tab..
\r- Carriage return..
\b- Backspace..
\f- Form feed..
\'- Single Quote..
\"- double quote..
\\-Backslash..

How do you print special characters?

2 Answers.
Press Ctrl + Shift + u..
Type in hexadecimal code for Unicode character you want to print..
Press enter..

How do you print symbols in Python?

To print any character in the Python interpreter, use a \u to denote a unicode character and then follow with the character code. For instance, the code for β is 03B2, so to print β the command is print['\u03B2'] . There are a couple of special characters that will combine symbols.

Chủ Đề