Creating Strings
In Python, strings can be created using either single quotes (‘ ‘) or double quotes (” “). Both are valid and function the same way.
a = 'Hello'
b = "World"
c = '''This is
a multi-line
string'''
Do it
Joining Strings
You can join (or concatenate) strings using the + operator or use methods like join() for more control.
# Using + operator
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print("Full Name (using +):", full_name)
# Using join() method
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print("Sentence (using join):", sentence)
# Concatenating strings and numbers (using str())
age = 25
message = "Age: " + str(age)
print(message)
# Using f-strings (Python 3.6+)
greeting = f"Hello, {first_name} {last_name}. You are {age} years old."
print("Greeting (using f-string):", greeting)
Do it
String Length
# Define some strings
str1 = "Python"
str2 = "Hello, World!"
str3 = " Space count "
# Get lengths using len()
print("Length of str1:", len(str1))
print("Length of str2:", len(str2))
print("Length of str3:", len(str3))
Do it
Accessing Characters
In Python, strings are indexed, which means each character has a position number.
# Define a string
text = "Python"
# Accessing characters by positive indexing
print("First character:", text[0]) # 'P'
print("Second character:", text[1]) # 'y'
print("Last character (positive index):", text[5]) # 'n'
# Accessing characters by negative indexing
print("Last character (negative index):", text[-1]) # 'n'
print("Second last character:", text[-2]) # 'o'