HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Python & Perl: Basic String Operations

Advertise Here For Profit

Xah Lee, 2005-01-10, 2011-03-21

Python

Substring

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]

String Length

Length of the string is len().

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

String Join & Repetition

Strings can be joined by a plus sign +.

print "this" + " that"

String can be repeated using *.

print "this" * 2

Perl

Substring

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

String Length

Length of string is length().

print length('abc');

String Join & Repetition

In Perl, string join is done with a dot.

$astr= "this" . "that";

String repeatition is done with the x operator:

print 'abc' x 2;
blog comments powered by Disqus