Python Strings

In Python, strings are used to represent a sequence of characters. They can be written using single or double quotes and can include letters, numbers, and special characters.

1string_literal = "Hello, World!" 2string_literal_single_quote = 'Hello, World!'

Python also provides a number of built-in methods for manipulating strings, such as concatenation, slicing, and formatting. These methods allow you to perform a wide range of operations on strings, such as changing the case, removing whitespace, or searching for substrings.

1string_literal = "Hello, World!" 2print(string_literal.upper()) # Output: "HELLO, WORLD!" 3print(string_literal.replace("World", "Python")) # Output: "Hello, Python!"

In addition to these built-in methods, Python also provides several string formatting techniques that allow you to insert values into a string. The most commonly used methods are:

Python String formatting

% This operator is used to format strings by replacing placeholders with values.

1name = "Denise" 2age = 25 3print("My name is %s and I am %d years old." % (name, age)) # Output: "My name is Denise and I am 25 years old."

format() method is used to format strings by replacing placeholders with values.

1name = "Denise" 2age = 25 3print("My name is {} and I am {} years old.".format(name, age)) # Output: "My name is Denise and I am 25 years old."

Python f string

f-strings feature introduced in Python 3.6, it allows you to embed expressions inside string literals.

1name = "Denise" 2age = 25 3print(f"My name is {name} and I am {age} years old.") # Output: "My name is Denise and I am 25 years old."