Strings in Python
A string is a sequence of characters used to store text in Python.
Examples:
name = "Uday" city = 'Janakpur' message = "Hello World"
The data type of a string is str.
name = "Uday" print(type(name))
Output:
<class 'str'>
1. Creating Strings
Python allows strings to be created using single or double quotes.
name = "Uday" city = 'Janakpur'
Both are valid.
You can also use triple quotes for multi-line strings:
message = """Hello Welcome to Python This is a string."""
2. String Indexing
Each character in a string has an index.
Python starts indexing from 0.
name = "Python"
P y t h o n 0 1 2 3 4 5
Access a character:
print(name[0]) print(name[2])
Output:
P t
3. Negative Indexing
Python also supports negative indexes.
P y t h o n -6 -5 -4 -3 -2 -1
Example:
name = "Python" print(name[-1]) print(name[-2])
Output:
n o
4. String Slicing
Slicing is used to extract a part of a string.
Syntax:
string[start:end]
Example:
text = "Python" print(text[0:3])
Output:
Pyt
The ending index is not included.
More examples
text = "Python" print(text[:3]) print(text[2:]) print(text[1:5])
Output:
Pyt thon ytho
5. String Concatenation
Concatenation means joining strings together.
Use +:
first_name = "Uday" last_name = "Raut" full_name = first_name + " " + last_name print(full_name)
Output:
Uday Raut
6. String Repetition
Use * to repeat a string.
text = "Hello " print(text * 3)
Output:
Hello Hello Hello
7. Finding String Length
Use the len() function.
text = "Python" print(len(text))
Output:
6
Spaces are also counted:
text = "Hello World" print(len(text))
Output:
11
8. Changing String Case
upper()
Converts text to uppercase.
text = "hello world" print(text.upper())
Output:
HELLO WORLD
lower()
Converts text to lowercase.
text = "HELLO WORLD" print(text.lower())
Output:
hello world
capitalize()
Capitalizes the first character.
text = "python programming" print(text.capitalize())
Output:
Python programming
title()
Capitalizes the first letter of each word.
text = "python programming language" print(text.title())
Output:
Python Programming Language
9. Removing Spaces
strip()
Removes spaces from both ends.
text = " Hello World " print(text.strip())
Output:
Hello World
lstrip()
Removes spaces from the left.
text = " Hello" print(text.lstrip())
rstrip()
Removes spaces from the right.
text = "Hello " print(text.rstrip())
10. Searching in a String
find()
Finds the position of a substring.
text = "Hello World" print(text.find("World"))
Output:
6
If the text is not found:
print(text.find("Python"))
Output:
-1
11. Checking String Content
startswith()
text = "Python Programming" print(text.startswith("Python"))
Output:
True
endswith()
text = "Python Programming" print(text.endswith("Programming"))
Output:
True
12. Replacing Text
Use replace().
text = "I like Java" new_text = text.replace("Java", "Python") print(new_text)
Output:
I like Python
13. Splitting a String
split() converts a string into a list.
text = "Python is easy" words = text.split() print(words)
Output:
['Python', 'is', 'easy']
You can also specify a separator:
data = "apple,banana,mango" fruits = data.split(",") print(fruits)
Output:
['apple', 'banana', 'mango']
14. Joining Strings
join() combines multiple strings.
words = ["Python", "is", "easy"] sentence = " ".join(words) print(sentence)
Output:
Python is easy
15. String Formatting
f-strings
The most common modern way to format strings is an f-string.
name = "Uday" age = 21 print(f"My name is {name} and I am {age} years old.")
Output:
My name is Uday and I am 21 years old.
You can also perform calculations:
a = 10 b = 20 print(f"Sum = {a + b}")
Output:
Sum = 30
16. Escape Characters
Escape characters are used to represent special characters inside strings.
New line \n
print("Hello\nWorld")
Output:
Hello World
Tab \t
print("Name:\tUday")
Output:
Name: Uday
Backslash \\
print("C:\\Users\\Uday")
Output:
C:\Users\Uday
Double quote \"
print("He said \"Hello\"")
Output:
He said "Hello"
17. Multiline Strings
Triple quotes allow strings to span multiple lines.
message = """ Welcome to Python. Python is easy to learn. Python is powerful. """ print(message)
18. Strings Are Immutable
Strings cannot be changed directly after they are created.
This will cause an error:
text = "Python" text[0] = "J"
Instead, create a new string:
text = "Python" text = "J" + text[1:] print(text)
Output:
Jython
19. Checking Characters in a String
Use in and not in.
text = "Python" print("P" in text) print("Java" in text)
Output:
True False
Example:
email = "student@gmail.com" print("@" in email)
Output:
True
20. Useful String Methods
| Method | Purpose |
|---|---|
upper() | Convert to uppercase |
lower() | Convert to lowercase |
capitalize() | Capitalize first character |
title() | Capitalize each word |
strip() | Remove spaces from both ends |
replace() | Replace text |
find() | Find text position |
split() | Split string into a list |
join() | Join strings |
startswith() | Check beginning |
endswith() | Check ending |
count() | Count occurrences |
len() | Find string length |
Complete Example
name = "Uday" course = "Python Programming" print("Name:", name) print("Course:", course) print("Length:", len(course)) print("Uppercase:", course.upper()) print("Lowercase:", course.lower()) print("First Character:", course[0]) print("Last Character:", course[-1]) print("Python" in course)
Remember
String ↓ Text / Characters ↓ "Hello" 'Python' """Multi-line text"""
String = a sequence of characters used to store and process text in Python.