str
In Python, strings are used to store text. A string is always surrounded by either single quotes (' '
) or double quotes (" "
). Both work the same way — you can use whichever you prefer, just be consistent.
name = "Dulanya"
greeting = 'Hello, world!'
print(name) # Output: Dulanya
print(greeting) # Output: Hello, world!
Sometimes you want to include quotes inside your string. Here are different ways to do that:
quote = "It's a sunny day."
print(quote) # Output: It's a sunny day.
dialogue = 'She said, "Hello!"'
print(dialogue) # Output: She said, "Hello!"
\\
)quote = 'It\\'s a sunny day.'
dialogue = "She said, \\"Hello!\\""
print(quote) # Output: It's a sunny day.
print(dialogue) # Output: She said, "Hello!"
story = """He said, "It's a great day!" and left."""
print(story)
# Output: He said, "It's a great day!" and left.
In Python, a string is not exactly a list, but it behaves like a list of characters in many ways.
You can think of a string as a sequence of characters, where each character has an index starting from 0.
word = "Hello"
print(word[0]) # Output: H
print(word[1]) # Output: e
Since a string is a sequence of characters, you can loop through each character one by one using a for
loop. This is helpful when you want to check, modify, or process every character in a string.