What is String?
- String is a datatype.
- String is represented as 'str' in python.
- String is collection of characters - Characters can be anything, including alphabets, special characters and numbers.
- String is mentioned with single quotes or double quotes.
- If we want to print multilines, we should give triple - single / double quotes.
- String is index based.
- Index starts from Zero.
- In Python, we have negative indexing too. Negative Indexing starts from right to left [Last Letter to First Letter].
- Index of First letter is 0.
- Index of Last Letter is -1.
- Slicing Operator, Step Operator.
name = "Python"
language = 'Programming'
message = """Welcome to Python"""
1. String Basics
A string can contain:
- Strings are immutable.
- String contain Alphabets (A–Z, a–z), Numbers (0–9), Special characters (@, #, $, %), Spaces.
- Strings support indexing and slicing.
- Python provides several built-in string methods.
- Strings support iteration using loops.
2. String Immutability
Strings are immutable in Python. This means we cannot directly modify individual characters after creating a string.
text = "Python"
# This will cause TypeError
text[0] = "J"
text = "Python"
text = "J" + text[1:]
print(text) //Jthon
3. String Formatting in Python
String formatting is used to insert variables into strings.
using f-string
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
Using format()
name = "John"
print("Hello, {}".format(name))
Using % formatting
name = "John"
print("Hello, %s" % name)
String Methods:
a.Case conversion methods like
text = "Hello PYTHON"
print(text.lower())
text = "Hello Python"
print(text.upper())
text = "python programming"
print(text.capitalize())
b.Replacement and splitting methods
text = "Python is easy"
print(text.split())
text = "I like Java"
print(text.replace("Java", "Python"))
c.Searching methods
text = "Mahendra Singh Dhoni"
print(text.find("a"))
text = "virat kohli"
print(text.startswith("Virat"))
text = "rohit sharma"
print(text[6:])
print(text[-6:])
print(text.endswith("sharma"))
text = "apple"
print(list(text))
text = "apple"
object - how do you prove this technically?
print(type(text))
print(list(text)) #list
text = " Python "
print(len(text)) //5
print(type(text.strip())) //python -remove white space
print(type(print())) //nonetype
- strip - return datatype
- function - return datatype
- Function - What is function, Arguments, return datatype
d.Checking methods
phone = '121212121'
print(phone.isalnum())
print(phone.isalpha())
print(phone.isdecimal())
standard = 'VIII
print(standard.isdecimal())
print(standard.isdigit())
print(standard.isnumeric())
standard = "42"
superscript = "2³"
fraction = "¾"
print(standard.isdecimal(), standard.isdigit()) # True, True
print(superscript.isdecimal(), superscript.isdigit()) # False, True
print(fraction.isdecimal(), fraction.isdigit()) # False, False
Top comments (0)