Introduction π
Strings are one of the most essential data types in Python. A string represents a sequence of characters used to store and manipulate text. Whether you're printing messages, handling user input, or processing data β strings are everywhere!
Note
1. Creating Strings βοΈ
You can create strings in multiple ways:
create_strings.py
s1 = "Hello"
s2 = 'Python'
s3 = """This is
a multi-line string"""
print(s1)
print(s2)
print(s3)- Single quotes β 'Hello'
- Double quotes β "Hello"
- Triple quotes β for multi-line text
2. String Indexing π―
Each character in a string has an index (position).
indexing.py
text = "Python"
print(text[0]) # P
print(text[3]) # h
print(text[-1]) # n (last character)Note
3. String Slicing βοΈ
Extract parts of a string using slicing.
slicing.py
word = "Python"
print(word[0:3]) # Pyt
print(word[2:5]) # tho
print(word[:4]) # Pyth
print(word[2:]) # thon
print(word[-3:]) # hon4. String Length π
Use len() to find the number of characters in a string.
length.py
msg = "Hello Python"
print(len(msg))5. String Concatenation β
Join two or more strings using the + operator.
concat.py
first = "Hello"
second = "World"
print(first + " " + second)Note
6. String Repetition π
repeat.py
print("Hi! " * 3)7. Escape Characters π§
Use backslashes to include special characters inside strings.
| Escape Code | Description | Example |
|---|---|---|
| \n | New Line | print("Hello\nWorld") |
| \t | Tab Space | print("A\tB") |
| \' | Single Quote | print('It\\'s Python') |
| \" | Double Quote | print("He said \\"Hi\\"") |
| \\ | Backslash | print("C:\\\\Path") |
escape_examples.py
print("Hello\nWorld")
print("He said \"Hi\"")8. String Methods π§°
Python provides powerful built-in methods for strings.
string_methods.py
msg = "hello python"
print(msg.upper()) # HELLO PYTHON
print(msg.lower()) # hello python
print(msg.title()) # Hello Python
print(msg.capitalize()) # Hello python
print(msg.replace("python", "world"))
print(msg.split()) # ['hello', 'python']Note
9. Checking Substrings π
substring.py
text = "Python programming"
print("Python" in text) # True
print("Java" in text) # False10. f-Strings (String Formatting) β¨
f-Strings allow you to embed variables directly inside strings.
fstring.py
name = "Sathish"
age = 25
print(f"My name is {name} and I am {age} years old.")Note
11. Multiline Strings π§΅
multiline.py
msg = """This is
a multiline
string in Python."""
print(msg)12. Real-World Example π
real_world_example.py
name = input("Enter your name: ")
greeting = f"Hello {name}, welcome to Python!"
print(greeting.upper())Conclusion π
You're now ready to explore deeper string topics like slicing, formatting, methods, or even regex! Just tell me the next topic you want. π