If you enjoyed this site, please consider donating $3. Any amount is appreciated. Thanks!

Python & Perl: Basic String Operations

2005-01-10

Python

In Python, strings can be joined by a plus sign “+”.

print "this" + " that"

String can be repeated using “*”.

print "this" * 2

Substring extraction is done by appending a bracket “[]” with begin and ending index.

a="this and that"
print a[3:6]

The index can be negative, which counts from the end.

a="this and that"
print a[3:-2]

Length of the string is “len()”.

a="this and that"
print len(a)

Python Doc

Python Doc

Python Doc

Perl

In Perl, string join is done with a dot.

$astr= "this" . "that";

String repeatition is done with the “x” operator:

print 'abc' x 2;

String extraction is done with “substr()”. The form is: “substr($myString, offset index, number of characters to extract)”.

print substr('abcdefg',2,3); # prints cde

Length of string is “length()”.

print length('abc');

perldoc -f substr

perldoc perlop

2005-01
© 2005 by Xah Lee.