Strings

Python Strings: Chapter 3 – Advanced String Operations

Hii, learners welcome to my blog CodeWithTanveer in this post i have learn about what is string in python.

Strings are one of the most fundamental data types in Python, and mastering them is essential for any programmer. In this chapter, we’ll explore advanced string operations, including string formatting, slicing, methods, and more.

1. String Formatting in Python

Python provides multiple ways to format strings, making it easier to embed variables and expressions.

a) Using format() Method

The format() method allows you to insert values into placeholders {}.

name = "Alice"  
age = 25  
message = "My name is {} and I am {} years old.".format(name, age)  
print(message)  

Output:

My name is Alice and I am 25 years old.  

b) f-Strings (Python 3.6+)

f-Strings provide a concise and readable way to format strings.

name = "Bob"  
score = 95.5  
message = f"Hello, {name}! Your score is {score}."  
print(message)  

Output:

Hello, Bob! Your score is 95.5.  

2. String Slicing

Slicing allows you to extract parts of a string using indices.

Syntax:

string[start:stop:step]  

Example:

text = "Python Programming"  

# Get first 6 characters  
print(text[0:6])  # Output: "Python"  

# Get every second character  
print(text[::2])  # Output: "Pto rgamn"  

# Reverse a string  
print(text[::-1])  # Output: "gnimmargorP nohtyP"  

3. String Methods

Python provides built-in methods to manipulate strings.

a) upper() and lower()

Converts string to uppercase or lowercase.

text = "Hello World"  
print(text.upper())  # Output: "HELLO WORLD"  
print(text.lower())  # Output: "hello world"  

b) strip()

Removes leading and trailing whitespace.

text = "   Python   "  
print(text.strip())  # Output: "Python"  

c) split() and join()

  • split() breaks a string into a list.
  • join() combines a list into a string.
fruits = "apple,banana,cherry"  
fruit_list = fruits.split(",")  
print(fruit_list)  # Output: ['apple', 'banana', 'cherry']  

new_str = "-".join(fruit_list)  
print(new_str)  # Output: "apple-banana-cherry"  

d) replace()

Replaces a substring with another.

text = "I like Java"  
new_text = text.replace("Java", "Python")  
print(new_text)  # Output: "I like Python"  

4. String Checks

a) startswith() and endswith()

Checks if a string starts or ends with a given substring.

filename = "document.pdf"  
print(filename.endswith(".pdf"))  # Output: True  

b) isalpha()isdigit()isalnum()

Checks if all characters are alphabets, digits, or alphanumeric.

print("Python".isalpha())  # True  
print("123".isdigit())     # True  
print("Python3".isalnum()) # True  

5. Escape Characters

Escape sequences allow special characters in strings.

Escape SequenceMeaning
\nNew line
\tTab
\\Backslash
\"Double quote
print("Hello\nWorld")  

Output:

Hello  
World  

6. Raw Strings

Raw strings ignore escape characters, useful for file paths and regex.

path = r"C:\Users\Name\Documents"  
print(path)  # Output: "C:\Users\Name\Documents"  

7. Multiline Strings

Use triple quotes (''' or """) for multiline strings.

poem = """  
Roses are red,  
Violets are blue,  
Python is awesome,  
And so are you!  
"""  
print(poem)  

Conclusion

Python strings are versatile and come with powerful built-in methods. From formatting to slicing and manipulation, mastering these techniques will make your coding journey smoother.

Practice these concepts with different examples to strengthen your understanding. Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *