Strings are sequences of characters, used to represent text in programming. In Python, strings are immutable, meaning once a string is created, its contents cannot be changed. Any operation that appears to modify a string actually creates a new string.
Creating Strings
You can create strings by enclosing characters in single quotes ('), double quotes ("), or triple quotes (''' or """). Triple quotes are useful for multi-line strings or docstrings.
python# Single quotes str1 = 'Hello, Python!' # Double quotes str2 = "Learning Python is fun." # Triple quotes for multi-line strings str3 = """This is a multi-line string. It preserves newlines.""" # Triple quotes also for single-line, but less common str4 = '''Another single-line string''' print(str1) print(str2) print(str3) print(type(str1)) # Output: <class 'str'>
String Concatenation
You can combine (concatenate) strings using the + operator. This creates a new string.
pythongreeting = "Hello" name = "Alice" full_greeting = greeting + ", " + name + "!" print(full_greeting) # Output: Hello, Alice! # You can also use the * operator to repeat a string repeated_string = "abc" * 3 print(repeated_string) # Output: abcabcabc
String Formatting
Combining strings with variables is a common task.
Python offers several ways to format strings:
-
f-strings (Formatted String Literals - Python 3.6+): This is the most modern and recommended way. Prefix the string with
forFand place variable names directly inside curly braces{}.pythonitem = "book" price = 19.99 message_f = f"The {item} costs ${price:.2f}." print(message_f) # Output: The book costs $19.99. -
str.format()method: Older but still widely used. Uses curly braces{}as placeholders.pythonmessage_format = "The {} costs ${:.2f}.".format(item, price) print(message_format) # Output: The book costs $19.99. -
Old-style
%formatting: Similar to C'sprintf. Less common in modern Python due to f-strings.pythonmessage_old = "The %s costs $%.2f." % (item, price) print(message_old) # Output: The book costs $19.99.
String Indexing and Slicing
Strings are ordered sequences, meaning each character has an index (position). Indexing starts at
-
- Indexing: Access a single character using square brackets
[].
- Indexing: Access a single character using square brackets
- Slicing: Extract a substring (a portion of the string) using
[start:end:step].
pythonmy_string = "Python Programming" # Accessing characters print(my_string[0]) # Output: P (first character) print(my_string[7]) # Output: P (character at index 7) print(my_string[-1]) # Output: g (last character, negative indexing) print(my_string[-12]) # Output: o (12th character from the end) # Slicing (end index is exclusive) print(my_string[0:6]) # Output: Python print(my_string[9:]) # Output: rogramming (from index 9 to the end) print(my_string[:6]) # Output: Python (from beginning to index 6) print(my_string[7:18]) # Output: Programming print(my_string[::2]) # Output: Pto rmai (every second character) print(my_string[::-1]) # Output: gnimmargorP nohtyP (reverse string)
Common String Methods
Python strings come with many useful built-in methods (functions that belong to an object):
len(string): Returns the length of the string.str.upper(): Returns a new string with all characters in uppercase.str.lower(): Returns a new string with all characters in lowercase.str.strip(): Returns a new string with leading and trailing whitespace removed.str.replace(old, new): Returns a new string with all occurrences ofoldreplaced bynew.str.split(delimiter): Returns a list of substrings split by the given delimiter.str.find(substring): Returns the lowest index of the substring if found, -1 otherwise.
pythonsentence = " Hello, Python World! " print(len(sentence)) # Output: 26 print(sentence.upper()) # Output: HELLO, PYTHON WORLD! print(sentence.lower()) # Output: hello, python world! print(sentence.strip()) # Output: Hello, Python World! print(sentence.replace("Python", "Java")) # Output: Hello, Java World! print("apple,banana,cherry".split(',')) # Output: ['apple', 'banana', 'cherry'] print("Python".find("tho")) # Output: 2 print("Python".find("xyz")) # Output: -1
Strings are fundamental for handling text data, which is ubiquitous in programming. Mastering their creation, manipulation, and formatting is a crucial skill.
Key Takeaways:
- Strings are immutable sequences of characters, enclosed in quotes.
- Concatenate with
+and repeat with*. - Use f-strings for modern and efficient string formatting.
- Access individual characters via indexing (
[index]) and substrings via slicing ([start:end]). - Utilize built-in string methods like
len(),upper(),lower(),strip(),replace(), andsplit()for common manipulations.