Python: String [Data Type]

What is a String?

String in Python is-

A sequence of characters written together.
Wrapped using single(‘) or double(“) quote.
Can contain any character in it, there is no limit.

Examples of String

“Hello! World”
‘Name of this site is Big Box Code’
“1234 is a valid positive integer”

Defining a String

We can wrap a sequence of characters with single or double quotes to define a string.

# Define a string
big_box_str = "Site name BigBoxCode"

# Check type and other properties
print("Type: ", type(big_box_str))
print("Length: ", len(big_box_str))

print(dir(big_box_str))
Python

Output:

Type:  <class 'str'>
Length:  20

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Plaintext

String Concatenation

Use the “+” (Plus) sign to concatenate a string with another.

full_str = "First part" + "second part" + "last part"

print(full_str)

site_name = "BigBoxCode"
site_url = "https://bigboxcode.com"

print("Name of the site is "" + site_name + "", and the URL is " + site_url)
Python

Output:

First partsecond partlast part
Name of the site is "BigBoxCode", and the URL is https://bigboxcode.com
Plaintext

Indexing in String

Characters in a string can be accessed by using the index, those characters are at. Indexing starts from Zero(0).

String Character Indexing
String Character Indexing

Case #1

We can directly access the string elements by using the index-

my_str = "Big Box Code"

print(my_str[0])
print(my_str[5])
print(my_str[11])
Python

Output:

B
o
e
Plaintext

Loop through String Elements

Case #1: Using for Loop

We can use a for loop and traverse through each element of a string.

my_str = "Big Box Code"

for c in my_str:
    print(c)
Python

Output:

B
i
g

B
o
x

C
o
d
e
Plaintext

Case #2: Using while Loop

We can use the while loop, start from the string index 0 to the last index to traverse elements of a string. The index of last element is (length of the string -1)

my_str = "Big Box Code"

# Start from index 0
str_index = 0

while str_index < len(my_str):
    char_at_str_index = my_str[str_index]
    
    print(f"Index={str_index} || Item: {char_at_str_index}")
    
    # Increase the index to the next
    str_index += 1
Python

Output:

Index=0 || Item: B
Index=1 || Item: i
Index=2 || Item: g
Index=3 || Item:
Index=4 || Item: B
Index=5 || Item: o
Index=6 || Item: x
Index=7 || Item:
Index=8 || Item: C
Index=9 || Item: o
Index=10 || Item: d
Index=11 || Item: e
Plaintext

Slicing String

We can get certain(specific) part of a string by slicing it. We need to provide the starting and ending index of the slice.

The last index is not included in the returned slice. The slice will be up to the previous index of last provided index.

Case #1

my_str = "Big Box Code"

# Get the string elements form index 0 to 4(=5-1) 
print(my_str[0:5])

# Get the string elements form index 2 to 4(=5-1) 
print(my_str[2:5])

# Stops as the end as the max limit is beyond the string index
print(my_str[4: 999])
Python

Output:

Big B
g B
Box Code
Plaintext

Check Sub-String Existence

We can check if a string contains a certain substring by using the keyword “in”. We get the result in boolean-

Case #1: Check if Sub-String Exists

my_str = "Big Box Code"

print("Box" in my_str)

print("Co" in my_str)

print("big" in my_str)
Python

Output:

True
True
False
Plaintext

Case #2: Use Boolean Result from “in”

my_str = "Big Box Code"

# Check if "Box" exist in my_str
if "Box" in my_str:
    print("Box found in my_str")
else:
    print("Box not found")

# Check if "Co" exist in my_str
if "Co" in my_str:
    print("Co found in my_str")
else:
    print("Co not found")

# Check if "big" exist in my_str
# it will return false as it does not match the case
if "big" in my_str:
    print("big found in my_str")
else:
    print("big not found")
Python

Output:

Box found in my_str
Co found in my_str
big not found
Plaintext

Transform String

my_str = "Big Box Code"

# Convert string to lower case
print(my_str.lower())

# Convert string to upper case
print(my_str.upper())

# Capitalize first letter of the string
print("some string for test".capitalize())
Python

Output:

big box code
BIG BOX CODE
Some string for test
Plaintext

Search and Replace

my_str = "Big Box Code"

print(my_str.replace("B", "*"))
print(my_str.replace("ode", ""))
Python

Output:

*ig *ox Code
Big Box C
Plaintext

Strip Whitespaces

my_str = " Big Box Code "

print(f"my_str: start|{my_str}|end")
print(f"my_str.lstrip(): start|{my_str.lstrip()}|end")
print(f"my_str.rstrip(): start|{my_str.rstrip()}|end")
print(f"my_str.strip(): start|{my_str.strip()}|end")
Python

Output:

my_str: start| Big Box Code |end
my_str.lstrip(): start|Big Box Code |end
my_str.rstrip(): start| Big Box Code|end
my_str.strip(): start|Big Box Code|end
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.