Python: Basic String Operations

By Xah Lee. Date: . Last updated: .

Substring

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

# 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().

# python 3

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

String Join and Repetition

Strings can be joined by a plus sign +.

# python 3

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

String can be repeated using *.

# python 3

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

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

Python 3

Lang Detail

  1. Print Version String
  2. Quoting String
  3. String Operations
  4. Format String
  5. Operators
  6. Object, ID, Type

Misc

  1. Traverse Directory
  2. Sort List, Matrix, Object
  3. Python 3: Map with Side Effect Doesn't Work If Result is Not Used
  4. Python 3 Closure
  5. Python 2 and 3 Difference