Python

What is the backslash in Python – or inverted backslash for

January 25, 2022

What is the backslash in Python – or inverted backslash for

In this article, we will learn what is the backslash in Python (\ or inverted backslash) and its ways of use in the language, commonly called backslash.

backslash in Python cover

What’s up programmer, how are you? Let’s learn more about Python!

When we encounter the backslash in Python code that is not a string, it indicates code continuation on newline

See the example:

a = 1
b = 2
c = 3
d = a + b \
+ c

print(d)

In this code we have the output of 6, which would be the same as if we had a code like this:

a = 1
b = 2
c = 3
d = a + b + c

print(d)

If you don’t add this backslash, Python will throw a syntax error

However, the code is not very intuitive using this special character, so think carefully about the situations you will use it

Another interesting feature of Python is that in parentheses in code statements, we don’t need to add the \

See this example:

a = 1
b = 2
c = 3
d = (a + 
b + 
c)

print(d)

Inside strings, \ has a different function, and combined with some characters has its functions established

  • \n: line break;
  • \t: tab character;
  • \b: backspace;
  • \r: return to beginning of line;
  • \\: represents a \;

See example with \n:

print("Testando a string em \n múltiplas linhas")

The output will be:

Testando a string em 
múltiplas linhas

Conclusion

In this article, we learned  what the backslash is for in Python 

We use it in several ways allied to some character in the middle of a string, which returns a special function running in it

In a normal line of code, we learned  that it lets us run the code continuity on another line

Want to learn more about Python? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x