String Manipulation in Python

String handling in Python is an important part of programming, as strings are one of the most common and commonly used data types in many applications. Here are some ways to handle strings in Python:

 

Declaring Strings

To declare a string in Python, you can use either single quotes or double quotes. Both single and double quotes are considered valid for creating strings.

Example:

str1 = 'Hello, World!'
str2 = "Python Programming"

 

Accessing Characters in a String

You can access a specific character in a string by using its index. The index starts from 0 and counts from left to right.

Example:

str = "Hello, World!"
print(str[0])    # Output: H
print(str[7])    # Output: W

 

String Slicing

String slicing allows you to retrieve a portion of the string using the syntax [start:end]. The character at the position start is included in the result, but the character at the position end is not.

Example:

str = "Hello, World!"
print(str[0:5])   # Output: Hello

 

String Length

To find the length of a string, you can use the len() function.

Example:

str = "Hello, World!"
print(len(str))   # Output: 13

 

Concatenating Strings

You can concatenate two or more strings together using the + operator.

Example:

str1 = "Hello"
str2 = " World!"
result = str1 + str2
print(result)   # Output: Hello World!

 

String Formatting

To format a string with replacement values, you can use the format() method or f-string (Python 3.6 and above).

Example:

name = "Alice"
age = 30
message = "My name is {}. I am {} years old.".format(name, age)
print(message)   # Output: My name is Alice. I am 30 years old.

# Chuỗi f-string
message = f"My name is {name}. I am {age} years old."
print(message)   # Output: My name is Alice. I am 30 years old.

 

String Methods

Python provides many useful methods for string manipulation, such as split(), strip(), lower(), upper(), replace(), join(), and more.

Example:

str = "Hello, World!"
print(str.split(","))   # Output: ['Hello', ' World!']
print(str.strip())   # Output: "Hello, World!"
print(str.lower())   # Output: "hello, world!"
print(str.upper())   # Output: "HELLO, WORLD!"
print(str.replace("Hello", "Hi"))   # Output: "Hi, World!"

 

String handling in Python allows you to perform complex and efficient operations on textual data.