Python: String Operations

By Xah Lee. Date: . Last updated: .

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 and 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

Python: String Methods

Python: String Methods