» Quick Introduction to Python » 1. Basics » 1.8 Strings

String Operations

Create a String

x = "lite"
x = 'rank'
x = str(12345) # convert number to string

x = '''This creates
a multiline string
example.'''

x = "*" * 5 # Repeat '*' five times, it produces "*****"

x = ",".join(["lite", "rank"]) # it produces "lite,rank"

Access Substrings

s = "literank.com"
print(s[4:8]) # rank, from character at index 4 to chracter at index 7 (the end position 8 is excluded)

You many provide negative numbers for start and end positions.

s = "literank.com"
print(s[8:-1]) # .co

If you do not provide any start or end position, the [:] slice operation returns the whole string.

s = "literank.com"
print(s[:]) # literank.com

Concatenate Strings

x, y = "lite", "rank"

print(x + y) # literank

x += y
print(x) # literank

# insert at specific index
x = "litrank"
c = 'e'
idx = 3
print(x[:idx]+c+x[idx:]) # literank

Replace Substrings

x = "literank.org"
print(x.replace("org", "com")) # literank.com


# replace only 1 occurrence
x = "literank.org doesn't end with org"
print(x.replace("org", "com", 1)) # literank.com doesn't end with org

Split Strings

x = "lite,rank,.com"
print(x.split(',')) # ['lite', 'rank', '.com']

# Limit to 1 split "cut" only
print(x.split(',', 1)) # ['lite', 'rank,.com']

If you don't provide any argument to split() function, it would take white spaces as delimiter.

x = "l i t e r a n    k"
print(x.split()) # ['l', 'i', 't', 'e', 'r', 'a', 'n', 'k']

Transform Strings

x = 'LiteRank'
print(x.lower()) # literank
print(x.upper()) # LITERANK

y = "rank"
print(y.capitialize()) # Rank

You can reverse a string by specifying the slicing step as -1.

z = "hello world"
print(z[::-1]) # dlrow olleh

Convert to other Types

x, y = '58', '58.12'

print(int(x)) # 58
print(float(y)) # 58.12
print([*y]) # ['5', '8', '.', '1', '2']

Code Challenge

Try to modify the code provided in the editor to make it print I'm LEARNING on literank.com now.

Loading...
> code result goes here
Prev
Next