| id | title | sidebar_label | sidebar_position | tags | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
python-string |
String in Python |
String in Python |
7 |
|
In Python, a string is a sequence of characters enclosed within single ('), double ("), or triple quotes (''' ''' or """ """).
It is used to store and manipulate textual data.
str1 = 'Hello'
str2 = "World"
str3 = '''This is a multi-line string.'''Strings can be created in several ways:
name = "Dhruba"
message = 'Welcome to Python'
multiline = """This
is a
multiline string."""Indexing: Access characters by position (starting at index 0).
text = "Python"
print(text[0]) # P
print(text[-1]) # nSlicing: Extract a part of the string.
print(text[0:3]) # Pyt
print(text[::2]) # Pto
print(text[1:-1]) # ytho| Method | Description |
|---|---|
upper() |
Converts all characters to uppercase |
lower() |
Converts all characters to lowercase |
strip() |
Removes spaces from both ends |
replace(a, b) |
Replaces a with b |
startswith(val) |
Checks if string starts with val |
endswith(val) |
Checks if string ends with val |
find(val) |
Finds the first index of val |
count(val) |
Counts occurrences of val |
msg = " Hello Python "
print(msg.upper()) # HELLO PYTHON
print(msg.strip()) # Hello Python
print(msg.replace("Python", "JS")) # Hello JSConcatenation with +:
first = "Hello"
second = "World"
print(first + " " + second) # Hello WorldRepetition with *:
print("Hi! " * 3) # Hi! Hi! Hi!Check for substring presence:
text = "Python is fun"
print("fun" in text) # True
print("Java" not in text) # Truename = "Dhruba"
age = 22
print(f"My name is {name} and I am {age} years old.")print("My name is {} and I am {} years old.".format(name, age))print("My name is %s and I am %d years old." % (name, age))Escape characters add special formatting in strings:
| Escape | Meaning |
|---|---|
\n |
New line |
\t |
Tab space |
\\ |
Backslash |
\' |
Single quote |
\" |
Double quote |
print("Hello\nWorld") # Line break
print("Name:\tDhruba") # TabTriple quotes allow multi-line text:
message = """This is line 1
This is line 2
This is line 3"""
print(message)name = input("Enter your name: ")
print(f"Welcome, {name}!")text = "banana"
print(text.count("a")) # 3with open("file.txt") as f:
data = f.read()
print(data.lower())email = "user@example.com"
if email.endswith("@example.com"):
print("Valid domain")- Strings are immutable sequences of characters.
- Support indexing, slicing, concatenation, and repetition.
- Useful methods help in text processing.
- Use escape sequences for formatting.
- Use f-strings or
format()for clean formatting.