Python: Basic String Operations

By Xah Lee. Date: . Last updated: .

Substring

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

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

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 3

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

String Join and Repetition

Strings can be joined by a plus sign +.

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

# string join
print("this" + " that")

String can be repeated using *.

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

# repeat string
print("this" * 2)               # thisthis

If you have a question, put $5 at patreon and message me.