Ways to print escape characters in python

PythonServer Side ProgrammingProgramming

In this article, we are going to see how we can print the escape characters in Python. I think you know what escape characters are? Let's see what escape characters for those who don't know are?

Escape characters are used for the individual meanings in strings. If we want to include a new line, tab space, etc., in strings, we can use these escape characters. Let's see some examples.

Example

 Live Demo

## new line
new_line_string = "Hi\nHow are you?"

## it will print 'Hi' in first line and 'How are you?' in next line
print(new_line_string)

Output

If you run the above program, it will produce the following results.

Hi
How are you?

We have many escape characters in Python like \n, \t, \r, etc., What if we want to print a string which contains these escape characters? We have to print the string using repr() inbuilt function. It prints the string precisely what we give. Let's see an example.

Example

 Live Demo

## string
string = "Hi\nHow are you?\nFine."

## exact string will be printed
print(repr(string))

Output

If you run the above program, it will produce the following results.

'Hi\nHow are you?\nFine.'

We can also print the exact string without using repr() function. We have initialized string using r or R string trigger. Let's see it with an example.

Example

 Live Demo

## string trigger
string = R"Hi\nHow are you?\nFine."

## exact string will be printed
print(string)

Output

If you execute the above program, it will produce the following results.

Hi\nHow are you?\nFine.

We can also use the small alphabet of R and will get the same result.

Conclusion

I hope you learn how to print the escape characters in Python. If you have any doubts regarding the article, please mention them in the comment section.

raja
Published on 09-Jul-2019 07:01:52
Advertisements