It is a collection of homogenous and heterogeneous character. Enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """).
Strings can be created by enclosing characters in quotes.
single_quoted_string = 'Hello'
double_quoted_string = "Hello"
triple_quoted_string = '''Hello, world!'''
another_triple_quoted_string = """Hello, world!"""
It is a process of fetching or extracting one single character at a time from the given string by giving reference of position or index value.
s = "Hello"
print(s[0]) # Output: H
print(s[1]) # Output: e
print(s[-1]) # Output: o (last character)
It is a process of extracting continuous corresponding set of character else a substring from a given string.
s = "Hello, world!"
print(s[0:5]) # Output: Hello
print(s[:5]) # Output: Hello (same as s[0:5])
print(s[7:]) # Output: world! (from index 7 to the end)
print(s[-6:]) # Output: world! (last 6 characters)
Use the len() function to get the length of a string.
s = "Hello"
print(len(s)) # Output: 5
Python provides many built-in methods for strings. Here are some commonly used ones:
Changing Case:
s = "Hello, World!"
print(s.lower()) # Output: hello, world!
print(s.upper()) # Output: HELLO, WORLD!
print(s.capitalize()) # Output: Hello, world!
print(s.title()) # Output: Hello, World!
Searching and Replacing:
s = "Hello, world!"
print(s.find("world")) # Output: 7 (index of the first occurrence)
print(s.replace("world", "Python")) # Output: Hello, Python!
Splitting and Joining:
s = "Hello, world!"
words = s.split(", ") # Splits into a list of substrings
print(words) # Output: ['Hello', 'world!']
print(", ".join(words)) # Output: Hello, world! (joins list elements into a string)
Python provides multiple ways to format strings.
Using ‘% ’ Operator:
name = "Alice"
age = 30
s = "My name is %s and I am %d years old." % (name, age)
print(s) # Output: My name is Alice and I am 30 years old.
Using ‘format()’ Method:
name = "Alice"
age = 30
s = "My name is {} and I am {} years old.".format(name, age)
print(s) # Output: My name is Alice and I am 30 years old.
Using f-Strings:
name = "Alice"
age = 30
s = f"My name is {name} and I am {age} years old."
print(s) # Output: My name is Alice and I am 30 years old.
Escape Characters:
Escape characters are used to include special characters in strings.
print("He said, \"Hello, world!\"") # Output: He said, "Hello, world!"
print('It\'s a beautiful day.') # Output: It's a beautiful day.
print("Line1\nLine2") # Output: Line1
# Line2
print("Column1\tColumn2") # Output: Column1 Column2