Category: python
Python Strings
Published on 24 Jul 2026
Explanation
A string is a sequence of characters enclosed in single quotes (' '), double quotes (" "), or triple quotes
Code:
text = 'Python Programming'
print(text)
print('First Character:', text[0])
print('Second Character:', text[1])
print('Last Character:', text[-1])
for ch in text:
print(ch)
Explanation
String slicing allows you to extract a portion of a string using the syntax string[start:end:step]. The start index is inclusive,
Code:
text = 'Python Programming' print(text[0:6]) print(text[7:18]) print(text[:6]) print(text[7:]) print(text[-11:]) print(text[::-1]) print(text[::2])
Explanation
Python provides many built-in string methods to manipulate text. The upper() and lower() methods convert text to uppercase and lowercase.
Code:
text = ' python programming '
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.strip())
print(text.lstrip())
print(text.rstrip())
print(text.replace('python', 'Java'))
Explanation
Python provides several methods for searching and splitting strings. The find() method returns the index of the first occurrence of
Code:
sentence = 'Python is easy to learn'
print(sentence.find('easy'))
print(sentence.count('a'))
print(sentence.startswith('Python'))
print(sentence.endswith('learn'))
words = sentence.split(' ')
print(words)
result = '-'.join(words)
print(result)
Explanation
String formatting is used to create readable and dynamic output by inserting variable values into strings. Python supports concatenation using
Code:
name = 'John'
age = 28
salary = 55000.75
# Concatenation
print('Name: ' + name)
# format() method
print('Age: {}'.format(age))
print('Salary: {:.2f}'.format(salary))
# f-string
print(f'Employee Name: {name}')
print(f'Employee Age: {age}')
print(f'Salary: βΉ{salary:.2f}')