📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Strings in Python are sequences of characters enclosed in quotes. They can be enclosed in single quotes ('
), double quotes ("
), or triple quotes ('''
or """
). Strings are immutable, meaning their contents cannot be changed once created. This tutorial covers various operations and features of strings in Python.
Table of Contents
- Define String and Key Points
- Create String
- Access String Characters
- Change String Characters
- Concatenate Strings
- String Methods
- String Formatting
- String Slicing
- Loop Through a String
- String Operations
- String Methods
- Conclusion
Key Points
Strings in Python are sequences of characters enclosed in quotes. They can be enclosed in single quotes ('
), double quotes ("
), or triple quotes ('''
or """
).
Key points about strings:
- Immutable: Contents cannot be changed after creation.
- Indexed: Each character is accessible using its index.
- Sequence: Strings are sequences of characters.
1. Create String
Strings can be created by enclosing characters in single, double, or triple quotes.
Example
# Creating strings single_quote_str = 'Hello' double_quote_str = "Hello" triple_quote_str = '''Hello, this is a multi-line string.''' print(single_quote_str) # Output: Hello print(double_quote_str) # Output: Hello print(triple_quote_str) # Output: Hello, this is a multi-line string.
2. Access String Characters
String characters can be accessed using their index. Indexing starts at 0. Negative indexing is also supported.
Example
my_string = "Python" # Accessing characters print(my_string[0]) # Output: P print(my_string[3]) # Output: h # Negative indexing print(my_string[-1]) # Output: n print(my_string[-2]) # Output: o
3. Change String Characters
Since strings are immutable, you cannot change their characters directly. However, you can create a new string with the desired modifications.
Example
# Attempting to change a character (will raise an error) # my_string[0] = 'J' # TypeError: 'str' object does not support item assignment # Creating a new string with the desired changes new_string = 'J' + my_string[1:] print(new_string) # Output: Jython
4. Concatenate Strings
Strings can be concatenated using the +
operator or join()
method.
Example
str1 = "Hello" str2 = "World" # Using + operator concatenated_str = str1 + " " + str2 print(concatenated_str) # Output: Hello World # Using join() method concatenated_str = " ".join([str1, str2]) print(concatenated_str) # Output: Hello World
5. String Methods
Python provides various built-in methods for string manipulation.
Example
sample_str = " Hello, World! " # strip() method print(sample_str.strip()) # Output: Hello, World! # lower() method print(sample_str.lower()) # Output: hello, world! # upper() method print(sample_str.upper()) # Output: HELLO, WORLD! # replace() method print(sample_str.replace("World", "Python")) # Output: Hello, Python! # split() method print(sample_str.split(",")) # Output: [' Hello', ' World! ']
6. String Formatting
Python supports several ways to format strings, including f-strings
, format()
, and %
operator.
Example
name = "Ravi" age = 25 # Using f-strings formatted_str = f"My name is {name} and I am {age} years old." print(formatted_str) # Output: My name is Ravi and I am 25 years old. # Using format() method formatted_str = "My name is {} and I am {} years old.".format(name, age) print(formatted_str) # Output: My name is Ravi and I am 25 years old. # Using % operator formatted_str = "My name is %s and I am %d years old." % (name, age) print(formatted_str) # Output: My name is Ravi and I am 25 years old.
7. String Slicing
String slicing allows you to extract a part of a string by specifying a range of indices.
Example
my_string = "Hello, World!" # Slicing a string sliced_str = my_string[0:5] print(sliced_str) # Output: Hello # Slicing with negative indices sliced_str = my_string[-6:-1] print(sliced_str) # Output: World # Slicing with step sliced_str = my_string[0:12:2] print(sliced_str) # Output: Hlo ol
8. Loop Through a String
You can loop through the characters in a string using a for
loop.
Example
for char in "Python": print(char) # Output: # P # y # t # h # o # n
9. String Operations
Python strings support various operations, including checking for substrings, repeating, and more.
Example
my_string = "Python" # Checking for substring print("Pyt" in my_string) # Output: True print("Java" in my_string) # Output: False # Repeating a string repeated_str = my_string * 3 print(repeated_str) # Output: PythonPythonPython
10. String Methods
Python strings come with many built-in methods for various tasks. Here are some commonly used ones:
Example
example_str = "python programming" # capitalize() method print(example_str.capitalize()) # Output: Python programming # count() method print(example_str.count("p")) # Output: 2 # find() method print(example_str.find("gram")) # Output: 10 # isalpha() method print(example_str.isalpha()) # Output: False (because of the space) # isdigit() method print("12345".isdigit()) # Output: True # join() method print(", ".join(["apple", "banana", "cherry"])) # Output: apple, banana, cherry # startswith() method print(example_str.startswith("py")) # Output: True # endswith() method print(example_str.endswith("ing")) # Output: True
Conclusion
Strings are fundamental in Python and are used to store and manipulate text. Understanding how to create, access, modify, and perform operations on strings is essential for effective programming. This tutorial covered various aspects of strings, including creating, accessing, changing, and removing items, as well as advanced topics like string slicing, formatting, looping, and using built-in methods. By mastering these concepts, you can efficiently work with strings in your Python programs.
Comments
Post a Comment
Leave Comment