Book Image

Practical Maya Programming with Python

By : Robert Galanakis
Book Image

Practical Maya Programming with Python

By: Robert Galanakis

Overview of this book

Table of Contents (17 chapters)
Practical Maya Programming with Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Raw strings and string literals


In order to represent something like a new line in a string, you usually use a special series of characters: \n. "\n" is an escape sequence that indicates to whatever is using the string (writing to a file, printing to the console) that there is a newline present. For example, we can see "\n" in action quite easily:

>>> print 'hello\nworld'
hello
world

There are many escape sequences of which "\n" is just one. A problem can occur when you want an actual backslash in the string, such as for file paths on Windows operating systems. We need to escape the actual backslash with another backslash so the path will be interpreted properly. The first example in the following code is not escaped, so the results are printed on two lines. The second example is properly escaped, so the path prints properly, on a single line.

>>> print 'C:\newfolder'
C:
ewfolder
>>> print 'C:\\newfolder'
C:\newfolder

Because of this double-backslash inconvenience, we will sometimes use raw strings. A raw string is prefixed with the r character and it tells Python that the string should not be interpreted with escape sequences. In the following example, notice how the leading r causes the string to print properly, on a single line.

>>> print r'C:\newfolder'
C:\newfolder

I most commonly use raw strings to get around the double-backslash path issue on Windows, as I find the double-backslashes make the code significantly more cluttered.