.format()
)A string is a sequence of characters enclosed in single, double or triple quotes.
name = "Akash"
greeting = 'Hello'
multiline = """This
is
a multi-line string."""
Each character in a string has an index (starting at 0).
word = "Python"
print(word[0]) # P
print(word[5]) # n
You can use negative indexing too:
print(word[-1]) # n
print(word[-2]) # o
Slicing returns a substring:
word = "Python"
print(word[0:3]) # Pyt
print(word[:4]) # Pyth
print(word[2:]) # thon
print(word[-3:]) # hon
Syntax: string[start:end:step]
print(word[::2]) # Pto (skip every 2nd char)
Here are the most useful string methods:
Method | Description |
---|---|
lower() | Converts to lowercase |
upper() | Converts to uppercase |
capitalize() | Capitalizes first letter |
strip() | Removes whitespace |
replace(a, b) | Replaces a with b |
split() | Splits into a list |
join() | Joins list into string |
startswith() | Checks if string starts with value |
endswith() | Checks if string ends with value |
find() | Returns index of first match |
count() | Counts number of times substring appears |
Example:
text = " Python is awesome "
print(text.strip().upper().replace("AWESOME", "POWERFUL"))
# Output: PYTHON IS POWERFUL
f-strings provide a readable way to embed expressions inside strings using {}
.
name = "Akash"
age = 25
print(f"My name is {name} and I am {age} years old.")
Other way to format strings:
# .format()
print("Hello {}, your score is {}".format("Akash", 95))
# % formatting (older)
print("Your balance is %.2f" % 123.456)
message = """Dear Akash,
Welcoe to python!
"""
print(message)
Use \
for special characters:
Escape | Meaning |
---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
print("He Said, \"Python is fun!\"")
Prefix r
to disable escape characters:
print(r"C:\Users\Akash\Documents") # No \n interpreted
You cannot change a character in a string:
text = "hello"
# text[0] = 'H' ❌ will raise an error
Instead, create a new string:
text = "H" + text[1:] # Hello
Feature | Example |
---|---|
Indexing | "Python"[0] → P |
Slicing | "Python"[1:4] → yth |
Methods | "abc".upper() → ABC |
f-Strings | f"Hi {name}" |
Escape chars | \n , \t , \" |
Immutability | Strings cannot be modified in-place |
Input: akash kumar
Output: Akash Kumar | Total: 10 | Modified: Ak@sh Kum@r
Leave a Reply