MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1＆1

Python, Ruby, Perl: Basic String Operations

Xah Lee, ,

Python

Substring

Substring extraction is done by appending `[‹begin index›:‹end index›]`.

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

aa = "01234567"
print aa[2:4] # prints “23”. Does not include the end.

# negative index counts from end, starting with -1
bb = "this"
print bb[0:-2] # prints “th”

# when first index is omitted, default to 0.
# when second index is omitted, default to -1.
cc = "that"
print cc[:] # prints “that”
```

String Length

Length of the string is `len()`.

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

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

String Join ＆ Repetition

Strings can be joined by a plus sign `+`.

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

print "this" + " that"
```

String can be repeated using `*`.

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

print "this" * 2
```

Ruby

Substring

Substring extraction is done by appending a bracket `[‹index›,‹count›]`.

```#-*- coding: utf-8 -*-
# ruby

# substring
aa = "01234567"
p aa[0,2]                   # prints “01”. Start with index, then count of chars.

# negative index counts from end. -1 is last char.
p aa[-2,2]                   # prints “67”.
```

String Length

Length of the string is `.length` method.

```# -*- coding: utf-8 -*-
# ruby

a="this"
p a.length                      # 4
```

String Join ＆ Repetition

Strings can be joined by a plus sign `+`.

```# -*- coding: utf-8 -*-
# ruby

p "this" + " that"              # "this that"
```

String can be repeated using `*`.

```# -*- coding: utf-8 -*-
# ruby

print "this" * 2                # thisthis
```

Perl

Substring

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

```# -*- coding: utf-8 -*-
# perl

# substring. 2nd arg  is begin index, 3rd arg is count
print substr('012345', 2, 2); # prints 23
```

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 repetition is done with the operator `x`.

```print 'abc' x 2;
```