Python & Perl: Basic String Operations

Advertise Here

, 2005-01-10, 2011-07-22

Python

Substring

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

#-*- coding: utf-8 -*-
# python

a="this and that"
print a[3:6] # prints “s a”

b="01234567"
print b[3:6] # prints “345”

The easiest way to make sense of python's indexing is to to think that the index goes between the chars, not on the char, and index starts at 0.

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

a="this and that"
print a[3:-2] # prints “s and th”

String Length

Length of the string is len().

a="this"
print len(a) # 4

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= "under" . "stand";

String repeatition is done with the the letter x.

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