Notes
Categories

String in Python [ English ]

< Prev Next >

1. Introduction

A string in Python is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).

Strings are used to represent text data such as names, messages, and sentences.


2. Creating a String

Examples

name = "Python"
msg = 'Hello World'
text = """This is a multiline string"""

3. Characteristics of Strings


4. Accessing Characters

Indexing

text = "Python"

print(text[0])
print(text[3])

Output

P
h

Negative Indexing

print(text[-1])

Output

n

5. Slicing

text = "Python"

print(text[1:4])

Output

yth

Step in Slicing

print(text[0:6:2])

Output

Pto

6. String Immutability

text = "Python"

text[0] = "J"   # Error

👉 Strings cannot be modified directly.


7. String Operations

Concatenation (+)

print("Hello " + "World")

Repetition (*)

print("Hi " * 3)

Membership

print("Py" in "Python")

8. Looping Through String

text = "Python"

for ch in text:
    print(ch)

9. Common String Methods

Method Description
lower() Converts to lowercase
upper() Converts to uppercase
strip() Removes spaces
replace() Replaces text
split() Splits string
find() Finds position

Example

text = "hello"

print(text.upper())

10. String Functions

Function Description
len() Length of string
max() Highest character
min() Lowest character

11. Escape Characters

Escape Meaning
\n New line
\t Tab
\\ Backslash

Example

print("Hello\nWorld")

12. String Formatting

Using f-string

name = "Rahul"
age = 20

print(f"My name is {name} and I am {age}")

13. Important Points


14. Summary

< Prev Next >