Strings
Strings hold text, written between single or double quotes.
Syntax
text = 'Hello'
len(text)A string is a sequence of characters used for text. You can write strings with single quotes '...' or double quotes "..." — they behave the same.
Length and joining
len(text)gives the number of characters.- The
+operator joins (concatenates) strings. - The
*operator repeats a string.
Example
greeting = 'Hello'
name = 'World'
print(greeting + ', ' + name + '!')
print(len(greeting))
print('ha' * 3)
# Output:
# Hello, World!
# 5
# hahahaWhen to use it
- A web form stores a user's name and email as strings before validating and saving them.
- A log writer builds a timestamped string and appends it to a log file.
- A template engine concatenates strings to assemble HTML snippets dynamically.
More examples
Create and print strings
Shows single and double quote strings concatenated with + to form a sentence.
greeting = 'Hello'
name = "World"
message = greeting + ', ' + name + '!'
print(message)
# Output:
# Hello, World!Multi-line string with triple quotes
Uses triple quotes to define a multi-line string without explicit newline characters.
address = """
42 Oak Street
Suite 100
Austin, TX 78701
"""
print(address)String length and repetition
Demonstrates len(), the repetition operator *, and basic case-conversion methods.
word = 'Python'
print(len(word)) # 6
print(word * 3) # PythonPythonPython
print(word.lower()) # python
print(word.upper()) # PYTHON
Discussion