Learn Python Strings: The Ultimate Guide from Basics to Methods
Python Strings Made Easy! ๐
A beautiful and simple guide to Python strings and their methods.
1. Creating Strings (String เคฌเคจाเคจा) ✨
You can create strings in Python using single, double, or triple quotes. Triple quotes are great for multi-line strings.
# Single, double, and multi-line strings
string_single = 'Hello from single quotes!'
string_double = "Hello from double quotes!"
string_multi = """This is a multi-line
string, perfect for longer text."""
print(string_single)
print(string_double)
print(string_multi)
2. Accessing Characters - Indexing ๐๐ข
Access individual characters using their position (index). Positive indexing starts from 0, while negative indexing starts from -1 (the end).
my_word = "PYTHON"
# Positive indexing
print(f"First character: {my_word[0]}") # Output: P
# Negative indexing
print(f"Last character: {my_word[-1]}") # Output: N
3. Getting a Substring - Slicing ✂️
Slicing lets you get a part of a string (a substring) using the syntax [start:end]. The 'end' index is not included.
my_text = "Programming"
# Get a slice from index 0 up to 4
print(my_text[0:4]) # Output: Prog
# Get a slice from index 4 to the end
print(my_text[4:]) # Output: ramming
4. String Operators (+ and *) ➕⭐
You can join strings with + (concatenation) and repeat strings with * (repetition).
# Concatenation
full_name = "Priya" + " " + "Sharma"
print(full_name) # Output: Priya Sharma
# Repetition
laugh = "Ha" * 5
print(laugh) # Output: HaHaHaHaHa
5. Useful String Methods (เค़เคฐूเคฐी Methods) ๐ ️
Python provides many built-in methods to work with strings. Here are a few common ones.
sentence = "Learning Python is Fun!"
# Get the length
print(f"Length: {len(sentence)}")
# Convert to lowercase
print(sentence.lower())
# Convert to uppercase
print(sentence.upper())
# Replace a substring
print(sentence.replace('Fun', 'Awesome'))
# Split the string into a list of words
print(sentence.split())
Example Output:
Length: 23
learning python is fun!
LEARNING PYTHON IS FUN!
Learning Python is Awesome!
['Learning', 'Python', 'is', 'Fun!']
Happy Coding! Keep exploring Python. ๐
Comments
Post a Comment