Python Basics
Python Strings
String operations
Python Strings
Strings in Python are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.
Creating Strings
Strings can be created by enclosing characters inside single quotes, double quotes, or triple quotes:
# Single quotes
x = 'Hello'
# Double quotes
y = "World"
# Triple quotes for multiline
z = """This is a
multiline string"""
String Operations
You can use the + operator to concatenate strings:
a = "Hello"
b = "World"
c = a + " " + b
print(c) # Hello World
String Methods
Python has a set of built-in methods that you can use on strings:
# Upper case
txt = "Hello World"
print(txt.upper()) # HELLO WORLD
# Lower case
print(txt.lower()) # hello world
# Strip whitespace
txt = " Hello World "
print(txt.strip()) # "Hello World"
# Replace string
print(txt.replace("H", "J")) # Jello World
# Split string
print(txt.split()) # ['Hello', 'World']
String Formatting
Python uses format() method to format strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age)) # My name is John, and I am 36