Python String

Python Strings

In Python, a string is a sequence of characters enclosed in single, double, or triple quotes.

Creating Strings

# Single quotes
string1 = 'Hello'

# Double quotes
string2 = "Python"

# Triple quotes (multi-line string)
string3 = '''This is
a multi-line string'''

print(string1)  # Output: Hello
print(string2)  # Output: Python
print(string3)
        

String Concatenation

We can combine two strings using the + operator.

# String concatenation
first = "Hello"
second = "World"
result = first + " " + second
print(result)  # Output: Hello World
        

String Formatting

Python provides multiple ways to format strings.

# Using f-strings
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

# Using format()
print("My name is {} and I am {} years old.".format(name, age))
        

Common String Methods

  • upper() - Converts string to uppercase
  • lower() - Converts string to lowercase
  • strip() - Removes leading and trailing spaces
  • replace() - Replaces a substring with another
  • split() - Splits a string into a list
# Example of string methods
text = "  Hello Python  "
print(text.upper())   # Output: HELLO PYTHON
print(text.lower())   # Output: hello python
print(text.strip())   # Output: Hello Python
print(text.replace("Hello", "Hi"))  # Output: Hi Python
print(text.split())   # Output: ['Hello', 'Python']