Article by: Manish Methani
Last Updated: October 6, 2021 at 2:04pm IST
Strings are used to represent text data in Python. In Python, a string is represented by str
class. We can create a string by enclosing text data in single quotes ('
) or double quotes ("
).
Here's an example:
# Example of string x = 'Hello, World!' y = "This is a string." print(x) print(y)
Output:
Hello, World! This is a string.
We can perform various operations on strings in Python. Here are some common string operations:
+
operator.*
operator.len()
function.upper()
and lower()
methods.Here are some examples:
# Example of string operations x = 'Hello,' y = ' World!' z = x + y print(z) a = 'Hello,' b = a * 3 print(b) c = 'Python' print(c[0]) # access first character print(c[1:4]) # slice from index 1 to 4 print(len(c)) # length of string d = 'Python is awesome' print(d.upper()) # convert to upper case print(d.lower()) # convert to lower case
Output:
Hello, World! Hello,Hello,Hello, P yth 6 PYTHON IS AWESOME python is awesome
String formatting is used to create formatted strings. In Python, we can use the format()
method to format strings. We can specify placeholders in a string using curly braces {}
and pass values to those placeholders using the format()
method.
Here's an example:
# Example of string formatting x = 'John' y = 'Doe' z = 'My name is {} {}.'.format(x, y) print(z)
Output:
My name is John Doe.
We can also use f-strings to format strings in Python 3.6 and above:
# Example of f-string x = 'John' y = 'Doe' z = f'My name is {x} {y}.' print(z)
Output:
My name is John Doe.
We have covered the basics of Python Strings in this tutorial.