A string in Python is a sequence of characters enclosed within single quotes ('), double quotes ("), or triple quotes (''' or """). It is an immutable data type, meaning once created, it cannot be changed.
You can create a string using different types of quotes:
# Using single quotes
str1 = 'Hello'
# Using double quotes
str2 = "Hello"
# Using triple quotes (for multi-line strings)
str3 = '''Hello,
This is a multi-line string'''
str4 = """Hello,
This is also a multi-line string"""Python treats strings as sequences of characters, so you can access individual characters using indexing and retrieve a substring using slicing.
Each character in a string has a position (index), starting from 0.
text = "Python"
print(text[0]) # Output: P (first character)
print(text[-1]) # Output: n (last character)You can extract parts of a string using slicing.
text = "Python"
print(text[0:4]) # Output: Pyth (characters from index 0 to 3)
print(text[:3]) # Output: Pyt (same as [0:3])
print(text[3:]) # Output: hon (from index 3 to end)
print(text[::2]) # Output: Pto (every second character)You can join strings using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello WorldYou can repeat a string using the * operator.
text = "Hello "
print(text * 3) # Output: Hello Hello HelloPython provides several built-in methods to manipulate strings. the most commonly used Python String Methods along with examples for better understanding.
Converts all characters to uppercase.
text = "hello world"
print(text.upper()) # Output: HELLO WORLDConverts all characters to lowercase.
text = "HELLO WORLD"
print(text.lower()) # Output: hello worldCapitalizes the first letter of each word.
text = "hello world"
print(text.title()) # Output: Hello WorldCapitalizes only the first letter of the string.
text = "hello world"
print(text.capitalize()) # Output: Hello worldRemoves leading and trailing whitespace or characters.
text = " hello world "
print(text.strip()) # Output: "hello world"Replaces a substring with another.
text = "I love Java"
print(text.replace("Java", "Python")) # Output: I love PythonReturns the index of the first occurrence of the substring. Returns -1 if not found.
text = "hello world"
print(text.find("world")) # Output: 6Splits the string into a list based on the separator.
text = "apple,banana,mango"
print(text.split(",")) # Output: ['apple', 'banana', 'mango']Joins elements of an iterable (like a list) into a string.
words = ['Hello', 'World']
print(" ".join(words)) # Output: Hello WorldChecks if a string starts or ends with the given substring.
text = "python programming"
print(text.startswith("python")) # True
print(text.endswith("ing")) # TrueChecks if all characters in the string are alphabets.
text = "hello"
print(text.isalpha()) # True
text2 = "hello123"
print(text2.isalpha()) # FalseChecks if all characters in the string are digits.
num = "12345"
print(num.isdigit()) # Truename = "Alice"
age = 25
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))Strings in Python cannot be changed after creation. If you try to modify an existing string, it will create a new one.
text = "Hello"
text[0] = "J" # This will raise an error because strings are immutableTo modify a string, you must create a new one:
text = "Hello"
text = "J" + text[1:] # Output: "Jello"You can check if a substring exists in a string using the in keyword.
text = "Hello, World"
print("Hello" in text) # Output: True
print("Python" not in text) # Output: TruePython provides escape sequences for including special characters in strings.
| Escape Character | Meaning | Example |
|---|---|---|
\n |
Newline | "Hello\nWorld" |
\t |
Tab space | "Hello\tWorld" |
\' |
Single quote | 'It\'s a book' |
\" |
Double quote | "He said \"Hello\"" |
\\ |
Backslash | "C:\\path\\to\\file" |
print("Hello\nWorld") # Output: Hello (new line) WorldA raw string treats backslashes as normal characters.
text = r"C:\Users\Name"
print(text) # Output: C:\Users\Nametext = "Python"
for char in text:
print(char)Output:
P
y
t
h
o
n
You can convert numbers, lists, or other types to a string using str().
num = 123
text = str(num)
print(text, type(text)) # Output: "123" <class 'str'>text = """This is a
multi-line string."""
print(text)