🔤 Strings in Python¶
In Python, a string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes.
1. Definition and Initialization¶
Both single and double quotes work the same, and you can use them interchangeably. The triple quotes allow the string to span more than one line.
# single quotes
s1 = 'Hello, world!'
print(s1)
# double quotes
s2 = "Hello, world!"
print(s2)
# triple quotes
s3 = '''Hello,
world!'''
print(s3)
Hello, world! Hello, world! Hello, world!
2. String Concatenation¶
You can combine strings using the +
operator. This is called concatenation.
s1 = 'Hello,'
s2 = ' world!'
s3 = s1 + s2
print(s3) # prints: Hello, world
Hello, world!
3. String Length¶
You can find the length of a string using the len()
function.
s = 'Hello, world!'
print(len(s)) # prints: 13
4. Accessing String Characters¶
You can access individual characters of a string using indexing. Remember, Python uses 0-based indexing.
s = 'Hello, world!'
print(s[0]) # prints: H
print(s[7]) # prints: w
H w
You can also use negative indexing to start from the end.
s = 'Hello, world!'
print(s[-1]) # prints: !
!
5. String Slicing¶
You can extract a portion of a string using slicing. The general syntax is string[start:stop:step]
. If not provided, start defaults to the beginning of the string, stop defaults to the end of the string, and step defaults to 1.
s = 'Hello, world!'
print(s[0:5]) # prints: Hello
print(s[7:]) # prints: world!
print(s[::2]) # prints: Hlo ol!
Hello world! Hlo ol!
6. String Methods¶
Python provides several built-in methods for strings.
s = 'Hello, world!'
print(s.upper()) # prints: HELLO, WORLD!
print(s.lower()) # prints: hello, world!
print(s.replace('H', 'J')) # prints: Jello, world!
print(s.split(',')) # prints: ['Hello', ' world!']
HELLO, WORLD! hello, world! Jello, world! ['Hello', ' world!']
7. String Formatting¶
Python provides several ways to format strings. Here's an example using f-string formatting:
name = 'John'
age = 30
print(f"My name is {name} and I'm {age} years old.")
# prints: My name is John and I'm 30 years old.
My name is John and I'm 30 years old.
Remember, Python is a rich language and provides many more methods and operations for strings. This tutorial only covers the basics. For a comprehensive understanding, you should refer to Python's official documentation.