Strings in Perl and Python

2005-01-09

Python

Strings are enclosed using single quote or double quote. e.g.

a="this "
b='and that'
print a, b

To quote a string of multiple lines, use triple quotes. Example:

d="""this
will be printed
in 3 lines"""
print d

One can add r to front for “raw string”. That is, backslash characters will be interpreted as is, not as escapes.

c=r"this\n and that"
print c # prints a single line

Python Doc

Perl

Use single quote for literal string.

# use single quote for literal string
$a='this and
 that';
print $a; # result will contain line break

To have characters “\n” for newline and “\t” for tab, use double quote.

$a="this\nand that";
print $a; # result will contain line break

When double quote is used, variables inside the string will be evaluated.

$a=4;
$b = "this is $a";
print $b; # prints “this is 4”

You can also use the syntax “q(this n that)”, which is equivalent to “'this n that'”. The parenthesis can be any of “{}” or “[]”.

# the following are all identical
$a = q(this 'n' that);
$b = q[this 'n' that];
$c = "this 'n' that";
$d = 'this \'n\' that';
print $a, "\n";
print $b, "\n";
print $c, "\n";
print $d, "\n";

Similarly, double quote is equivalent with “qq()”.

# perl

$a=q(here, everything is literal, 
$what or \n or ' or " or not.);

$b=qq[here, variables $a will be
expanded, backslash act as escape \n (and "quotes" or parenthesis needn't be escaped).];

print $a, "\n";
print '-----------', "\n";
print $b, "\n";

perldoc perlop

perldoc -f qq

Was this page useful? If so, please do donate $3, thank you donors!
Home
Terms of Use
About
Advertise
Subscribe
Google
2005-01
© 2005 by Xah Lee.