Python String
What is a Python String?
In Python, a string is an ordered collection of characters enclosed in single quotes ('
) or double quotes ("
). Strings are immutable, which means that once defined, their contents cannot be changed directly. Strings enable text processing and manipulation in Python.
Syntax
To create a string, you can use:
- Single quotes:
'Hello'
- Double quotes:
"Hello"
- Triple quotes:
'''Hello'''
or"""Hello"""
(for multiline strings)
Examples
-
Single-line Strings:
str1 = 'Hello' str2 = "World" print(str1) # Output: Hello print(str2) # Output: World
Multi-line Strings:
multiline_str = """This is a multiline string.""" print(multiline_str)
Output:
This is a multiline string.
String Operations
-
Concatenation: Strings can be concatenated using the
+
operator to form a new string.+
operator.str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) # Output: Hello World
-
Repetition: A string can be duplicated multiple times using the
*
operator.str1 = "Hi! " print(str1 * 3) # Output: Hi! Hi! Hi!
-
Indexing: Access specific characters using their index. Indexing starts at
0
.str1 = "Python" print(str1[0]) # Output: P print(str1[-1]) # Output: n (last character)
-
Slicing: You can retrieve specific portions of a string using slicing syntax.
str1 = "Hello, World" print(str1[0:5]) # Output: Hello print(str1[:5]) # Output: Hello print(str1[7:]) # Output: World
String Methods
Python provides many built-in methods for string manipulation:
-
len()
: Get the length of a string.str1 = "Hello" print(len(str1)) # Output: 5
-
lower()
andupper()
: Change the case of a string using built-in methods .str1 = "Python" print(str1.lower()) # Output: python print(str1.upper()) # Output: PYTHON
-
strip()
: Remove leading and trailing whitespace.str1 = " Hello " print(str1.strip()) # Output: Hello
-
replace()
: Replace a substring with another string.str1 = "Hello, World" print(str1.replace("World", "Python")) # Output: Hello, Python
-
split()
: Split a string into a list based on a delimiter (default is space).str1 = "Python is fun" print(str1.split()) # Output: ['Python', 'is', 'fun']
-
find()
: Locate the initial position of a substring using this method.tr1 = "Python programming" print(str1.find("pro")) # Output: 7
-
in
Keyword: Check if a substring exists in a string.str1 = "Python programming" print("Python" in str1) # Output: True print("Java" in str1) # Output: False
Formatted Strings
Python provides ways to create formatted strings:
-
Using
f-strings
(Python 3.6+):name = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.")
-
Using
format()
:name = "Alice" age = 25 print("My name is {} and I am {} years old.".format(name, age))
Conclusion
Strings in Python are versatile and come with many built-in methods for manipulation. They are widely used in applications such as text processing, data formatting, and more.