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.

🟰 Assign String to a Variable

name = "Dulanya"
greeting = 'Hello, world!'
print(name) # Output: Dulanya
print(greeting) # Output: Hello, world!

💬 Quotes Inside Quotes

Sometimes you want to include quotes inside your string. Here are different ways to do that:

Use double quotes outside if your string has single quotes inside

quote = "It's a sunny day."
print(quote)  # Output: It's a sunny day.

Use single quotes outside if your string has double quotes inside

dialogue = 'She said, "Hello!"'
print(dialogue)  # Output: She said, "Hello!"

Escape the inner quotes using a backslash (\\)

quote = 'It\\'s a sunny day.'
dialogue = "She said, \\"Hello!\\""
print(quote)    # Output: It's a sunny day.
print(dialogue) # Output: She said, "Hello!"

📝 Multiline Strings

story = """He said, "It's a great day!" and left."""
print(story)
# Output: He said, "It's a great day!" and left.

🔤 Strings as a Sequence of Characters

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

🔄 Looping Through a String

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.