More About the Python Strings
In Python, strings are sequences of characters enclosed in single, double, or triple quotes. Strings are immutable, which means they cannot be changed after they are created. They are used for text manipulation, such as printing, processing, or formatting text data.
This guide will take you through the basics and advanced concepts of working with strings in Python, including string creation, manipulation, and methods.
Understanding Strings in Python
A string is a sequence of characters. It can be defined using single quotes (`'`), double quotes (`"`), or triple quotes (`'''` or `"""`) for multi-line strings.
my_string = "Hello, Python!" # Double quotes
print(my_string)
another_string = 'Welcome to Python!' # Single quotes
print(another_string)
multiline_string = '''This
is
a
multi-line
string.'''
print(multiline_string)
my_string = "Hello, Python!" # Double quotes
print(my_string)
another_string = 'Welcome to Python!' # Single quotes
print(another_string)
multiline_string = '''This
is
a
multi-line
string.'''
print(multiline_string)
Output:
Hello, Python!
Welcome to Python!
This
is
a
multi-line
string
Hello, Python!
Welcome to Python!
This
is
a
multi-line
string
Strings are immutable, which means you cannot change a string after it is created. If you need to change the contents of a string, you will have to create a new one.
String Slicing in Python
String slicing in Python allows you to extract parts of a string by specifying a range of indices. It's a powerful tool for working with strings, enabling you to retrieve substrings, reverse strings, or skip characters.
The basic syntax for string slicing is as follows:
string[start:end:step]
string[start:end:step]
- start: The starting index (inclusive) from where to begin slicing. If omitted, it defaults to the beginning of the string (index 0).
- end: The ending index (exclusive) where to stop slicing. If omitted, it defaults to the end of the string.
- step: The step size, which determines how many characters to skip. If omitted, it defaults to 1, meaning it takes every character between the start and end.
Basic Examples of String Slicing
text = "Python Programming"
# Extracting the first 6 characters
print(text[:6]) # Output: 'Python'
# Extracting characters from index 7 to the end
print(text[7:]) # Output: 'Programming'
# Extracting characters from index 0 to 6 (excluding 7)
print(text[:7]) # Output: 'Python'
# Extracting characters from index 0 to 5 (every second character)
print(text[0:6:2]) # Output: 'Pto'
# Extracting characters from the end using negative indexing
print(text[-11:]) # Output: 'Programming'
# Reversing the string using slicing
print(text[::-1]) # Output: 'gnimmargorP nohtyP'
text = "Python Programming"
# Extracting the first 6 characters
print(text[:6]) # Output: 'Python'
# Extracting characters from index 7 to the end
print(text[7:]) # Output: 'Programming'
# Extracting characters from index 0 to 6 (excluding 7)
print(text[:7]) # Output: 'Python'
# Extracting characters from index 0 to 5 (every second character)
print(text[0:6:2]) # Output: 'Pto'
# Extracting characters from the end using negative indexing
print(text[-11:]) # Output: 'Programming'
# Reversing the string using slicing
print(text[::-1]) # Output: 'gnimmargorP nohtyP'
In the example above:
- text[:6]: Slices from the start (index 0) to index 6 (exclusive), resulting in 'Python'.
- text[7:]: Slices from index 7 to the end, giving 'Programming'.
- text[0:6:2]: Slices from index 0 to index 6, but with a step of 2, so it picks every second character, resulting in 'Pto'.
- text[-11:]: Uses negative indexing to slice the string from the 11th character from the end to the end, which gives 'Programming'.
- text[::-1]: Reverses the string by stepping backwards, resulting in 'gnimmargorP nohtyP'.
Negative Indexing in String Slicing
Python supports negative indexing for strings, which allows you to start counting from the end of the string. The last character has an index of -1, the second-to-last character has an index of -2, and so on.
text = "Python Programming"
# Extract the last character
print(text[-1]) # Output: 'g'
# Extract the last 3 characters
print(text[-3:]) # Output: 'ing'
# Extract everything except the last character
print(text[:-1]) # Output: 'Python Programmin'
text = "Python Programming"
# Extract the last character
print(text[-1]) # Output: 'g'
# Extract the last 3 characters
print(text[-3:]) # Output: 'ing'
# Extract everything except the last character
print(text[:-1]) # Output: 'Python Programmin'
In this example:
- text[-1]: This extracts the last character of the string, 'g'.
- text[-3:]: This slices the last 3 characters, 'ing'.
- text[:-1]: This slices the string from the beginning up to, but not including, the last character, resulting in 'Python Programmin'.
Advanced String Slicing with Step
The step value in slicing allows you to skip characters while slicing. This can be used to create more complex patterns when working with strings.
text = "Python Programming"
# Slicing with a step of 2
print(text[::2]) # Output: 'Pto rgamn'
# Slicing in reverse order with a step of 3
print(text[::-3]) # Output: 'gnmrPnhy'
text = "Python Programming"
# Slicing with a step of 2
print(text[::2]) # Output: 'Pto rgamn'
# Slicing in reverse order with a step of 3
print(text[::-3]) # Output: 'gnmrPnhy'
In these examples:
- text[::2]: This slices the string from start to end, but skips every second character, resulting in 'Pto rgamn'.
- text[::-3]: This slices the string in reverse order, skipping every third character, producing 'gnmrPnhy'.
String Concatenation in Python
String concatenation in Python is the process of joining two or more strings together to form a single string. In Python, you can concatenate strings using the + operator.
1. Concatenating Strings Using the + Operator
You can combine two or more strings by using the + operator. This operation simply joins the strings together in the order you specify.
# Concatenating strings
greeting = "Hello"
name = "John"
message = greeting + " " + name
print(message) # Output: 'Hello John'
# Concatenating strings
greeting = "Hello"
name = "John"
message = greeting + " " + name
print(message) # Output: 'Hello John'
In the example above, the strings "Hello" and "John" are concatenated using the + operator, with a space between them. The result is the combined string 'Hello John'.
2. Concatenating Multiple Strings
You can concatenate as many strings as you need, simply by using the + operator between each string.
# Concatenating multiple strings
greeting = "Hello"
name = "John"
age = "25"
message = greeting + " " + name + ", you are " + age + " years old."
print(message) # Output: 'Hello John, you are 25 years old.'
# Concatenating multiple strings
greeting = "Hello"
name = "John"
age = "25"
message = greeting + " " + name + ", you are " + age + " years old."
print(message) # Output: 'Hello John, you are 25 years old.'
In this example, we concatenate four strings: "Hello", "John", "you are", and "25". The result is the full sentence 'Hello John, you are 25 years old.'.
3. Concatenating Strings with Variables
You can also concatenate strings that are stored in variables, just like in the examples above. This allows you to dynamically create messages or outputs based on user input or calculations.
# Concatenating strings stored in variables
first_name = "Jane"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: 'Jane Doe'
# Concatenating strings stored in variables
first_name = "Jane"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: 'Jane Doe'
In this case, the strings "Jane" and "Doe" are stored in the variables first_name and last_name. We then concatenate them to form the full name "Jane Doe".
4. Concatenating Strings with Numbers
If you want to concatenate numbers with strings, you need to convert the number to a string first. This can be done using the str() function.
# Concatenating strings with numbers
age = 30
message = "I am " + str(age) + " years old."
print(message) # Output: 'I am 30 years old.'
# Concatenating strings with numbers
age = 30
message = "I am " + str(age) + " years old."
print(message) # Output: 'I am 30 years old.'
In this example, the integer 30 is converted to a string using the str() function before concatenating it with other strings. This results in the message "I am 30 years old.".
5. Using f-Strings for Concatenation (String Interpolation)
In addition to using the + operator for concatenation, Python also supports f-strings, which provide a more readable and efficient way to include variables directly inside strings.
# Using f-strings for string concatenation
name = "Tom"
age = 28
message = f"My name is {name} and I am {age} years old."
print(message) # Output: 'My name is Tom and I am 28 years old.'
# Using f-strings for string concatenation
name = "Tom"
age = 28
message = f"My name is {name} and I am {age} years old."
print(message) # Output: 'My name is Tom and I am 28 years old.'
With f-strings, you can directly embed the values of variables (like name and age) inside the string, making your code more readable and concise.
6. Using join() Method for Concatenation
Another efficient way to concatenate strings is by using the join() method. This method is especially useful when you need to join multiple strings stored in an iterable (like a list).
# Using join() method
words = ["Hello", "world", "from", "Python"]
message = " ".join(words)
print(message) # Output: 'Hello world from Python'
# Using join() method
words = ["Hello", "world", "from", "Python"]
message = " ".join(words)
print(message) # Output: 'Hello world from Python'
In this example, the join() method joins all the strings in the list words with a space separator. The result is the string 'Hello world from Python'.
String Formatting in Python
String formatting in Python allows you to insert variables or expressions into strings dynamically. It is a powerful way to create more readable and flexible strings.
Python provides several methods for formatting strings, including:
- Old-Style Formatting (`%`): The older method, still supported but generally replaced by more modern alternatives.
- `str.format()` Method: A flexible approach introduced in Python 2.7 and Python 3.0.
- f-Strings (Formatted String Literals): The most modern and efficient way to format strings, introduced in Python 3.6.
1. Old-Style String Formatting (`%`)
The old-style string formatting uses the `%` operator to insert values into a string.
name = "Tom"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string) # Output: 'Name: Tom, Age: 30'
name = "Tom"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string) # Output: 'Name: Tom, Age: 30'
In the example above, the `%s` placeholder is used for a string, and `%d` is used for an integer.
2. `str.format()` Method
The `str.format()` method allows for more flexibility in string formatting.
name = "Bob"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string) # Output: 'Name: Bob, Age: 25'
name = "Bob"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string) # Output: 'Name: Bob, Age: 25'
You can also specify the order of parameters using index numbers:
formatted_string = "Name: {0}, Age: {1}".format(name, age)
print(formatted_string) # Output: 'Name: Bob, Age: 25'
formatted_string = "Name: {0}, Age: {1}".format(name, age)
print(formatted_string) # Output: 'Name: Bob, Age: 25'
3. f-Strings (Formatted String Literals)
f-Strings are the most modern and concise way to format strings, introduced in Python 3.6. They allow you to embed expressions inside string literals.
name = "Charlie"
age = 40
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string) # Output: 'Name: Charlie, Age: 40'
name = "Charlie"
age = 40
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string) # Output: 'Name: Charlie, Age: 40'
f-Strings also support inline expressions:
x = 10
y = 20
formatted_string = f"The sum of x and y is: {x + y}"
print(formatted_string) # Output: 'The sum of x and y is: 30'
x = 10
y = 20
formatted_string = f"The sum of x and y is: {x + y}"
print(formatted_string) # Output: 'The sum of x and y is: 30'
4. Formatting Numbers and Precision
You can also format numbers and control the precision in strings. Here's how you can do that with `str.format()` and f-strings:
pi = 3.14159
# Using str.format() to control precision
formatted_string = "Pi rounded to 2 decimal places: {:.2f}".format(pi)
print(formatted_string) # Output: 'Pi rounded to 2 decimal places: 3.14'
# Using f-strings to control precision
formatted_string = f"Pi rounded to 2 decimal places: {pi:.2f}"
print(formatted_string) # Output: 'Pi rounded to 2 decimal places: 3.14'
pi = 3.14159
# Using str.format() to control precision
formatted_string = "Pi rounded to 2 decimal places: {:.2f}".format(pi)
print(formatted_string) # Output: 'Pi rounded to 2 decimal places: 3.14'
# Using f-strings to control precision
formatted_string = f"Pi rounded to 2 decimal places: {pi:.2f}"
print(formatted_string) # Output: 'Pi rounded to 2 decimal places: 3.14'
When to Use Each Method?
- **Old-Style (`%`)**: Avoid using this method in new code unless you're working with legacy code.
- **`str.format()`**: Useful for Python versions before 3.6, or when needing more complex formatting.
- **f-Strings**: Recommended for Python 3.6 and later. They are simple, concise, and generally the fastest choice for string formatting.
Advanced String Formatting in Python
Beyond basic string formatting, Python allows more advanced formatting techniques that can be used to align, pad, and format strings and numbers in more sophisticated ways.
1. Padding and Aligning Strings
Python allows you to pad and align strings, which is especially useful for formatting tables or ensuring that text lines up neatly.
# Left-align a string
name = "Tom"
formatted_string = "{:<10}".format(name) # Left align with 10 spaces
print(formatted_string) # Output: 'Tom '
# Right-align a string
formatted_string = "{:>10}".format(name) # Right align with 10 spaces
print(formatted_string) # Output: ' Tom'
# Center-align a string
formatted_string = "{:^10}".format(name) # Center align with 10 spaces
print(formatted_string) # Output: ' Tom '
# Left-align a string
name = "Tom"
formatted_string = "{:<10}".format(name) # Left align with 10 spaces
print(formatted_string) # Output: 'Tom '
# Right-align a string
formatted_string = "{:>10}".format(name) # Right align with 10 spaces
print(formatted_string) # Output: ' Tom'
# Center-align a string
formatted_string = "{:^10}".format(name) # Center align with 10 spaces
print(formatted_string) # Output: ' Tom '
You can use these formatting techniques with strings to make sure they line up as desired.
2. Formatting Numbers with Padding
Numbers can also be formatted with padding, ensuring they align correctly when printed or displayed.
# Format numbers with padding
num = 42
formatted_string = "{:05d}".format(num) # Pad with leading zeros
print(formatted_string) # Output: '00042'
# Format float numbers with specific precision
pi = 3.141592653589793
formatted_string = "{:10.2f}".format(pi) # Format to 2 decimal places with padding
print(formatted_string) # Output: ' 3.14'
# Format numbers with padding
num = 42
formatted_string = "{:05d}".format(num) # Pad with leading zeros
print(formatted_string) # Output: '00042'
# Format float numbers with specific precision
pi = 3.141592653589793
formatted_string = "{:10.2f}".format(pi) # Format to 2 decimal places with padding
print(formatted_string) # Output: ' 3.14'
3. Using Expressions Inside f-Strings
One of the most powerful features of f-strings is the ability to use expressions directly inside the string literals.
x = 10
y = 20
formatted_string = f"The sum of {x} and {y} is: {x + y}"
print(formatted_string) # Output: 'The sum of 10 and 20 is: 30'
x = 10
y = 20
formatted_string = f"The sum of {x} and {y} is: {x + y}"
print(formatted_string) # Output: 'The sum of 10 and 20 is: 30'
4. Formatting Dates and Times
You can format dates and times using the `strftime` method or f-strings, which is useful when working with datetime objects.
from datetime import datetime
# Get the current date and time
now = datetime.now()
# Format the date
formatted_string = f"Today's date is {now:%B %d, %Y}" # Format as 'March 11, 2025'
print(formatted_string)
# Formatting with strftime method
formatted_string = now.strftime("Current time: %H:%M:%S") # Format as '14:30:45'
print(formatted_string)
from datetime import datetime
# Get the current date and time
now = datetime.now()
# Format the date
formatted_string = f"Today's date is {now:%B %d, %Y}" # Format as 'March 11, 2025'
print(formatted_string)
# Formatting with strftime method
formatted_string = now.strftime("Current time: %H:%M:%S") # Format as '14:30:45'
print(formatted_string)
This shows how to format dates directly inside f-strings or using the `strftime()` method.
5. Using Named Placeholders with `str.format()`
With `str.format()`, you can use named placeholders instead of relying on the position of arguments, which improves readability.
name = "Tom"
age = 30
formatted_string = "Name: {name}, Age: {age}".format(name=name, age=age)
print(formatted_string) # Output: 'Name: Tom, Age: 30'
name = "Tom"
age = 30
formatted_string = "Name: {name}, Age: {age}".format(name=name, age=age)
print(formatted_string) # Output: 'Name: Tom, Age: 30'
6. Specifying the Number of Decimal Places
You can specify the number of decimal places you want to display using both `str.format()` and f-strings.
# Using str.format() to control precision
pi = 3.14159
formatted_string = "Pi to 2 decimal places: {:.2f}".format(pi)
print(formatted_string) # Output: 'Pi to 2 decimal places: 3.14'
# Using f-strings to control precision
formatted_string = f"Pi to 2 decimal places: {pi:.2f}"
print(formatted_string) # Output: 'Pi to 2 decimal places: 3.14'
# Using str.format() to control precision
pi = 3.14159
formatted_string = "Pi to 2 decimal places: {:.2f}".format(pi)
print(formatted_string) # Output: 'Pi to 2 decimal places: 3.14'
# Using f-strings to control precision
formatted_string = f"Pi to 2 decimal places: {pi:.2f}"
print(formatted_string) # Output: 'Pi to 2 decimal places: 3.14'
7. Formatting with Thousands Separator
Python also allows you to format large numbers with thousands separators, making them easier to read.
large_number = 1000000
formatted_string = "{:,}".format(large_number)
print(formatted_string) # Output: '1,000,000'
large_number = 1000000
formatted_string = "{:,}".format(large_number)
print(formatted_string) # Output: '1,000,000'
The `:,` placeholder formats numbers with commas as thousands separators. This is especially useful for displaying large monetary or population values.
8. Custom String Formatting with `format()`
You can use the `format()` method to create custom formatting patterns, including padding, alignment, and more. Here's an example of a custom formatting using multiple options.
value = 1234.5678
formatted_string = "{:10.2f}".format(value) # 10 characters wide, 2 decimal places
print(formatted_string) # Output: ' 1234.57'
value = 1234.5678
formatted_string = "{:10.2f}".format(value) # 10 characters wide, 2 decimal places
print(formatted_string) # Output: ' 1234.57'
String Methods
Method | Description |
---|---|
strip() | Removes any leading and trailing whitespaces from the string. Ex: text.strip() |
lower() | Converts all characters in the string to lowercase. Ex: text.lower() |
upper() | Converts all characters in the string to uppercase. Ex: text.upper() |
replace() | Replaces all occurrences of a specified substring with another substring. Ex: text.replace('Python', 'World') |
split() | Splits the string into a list at each occurrence of the specified delimiter. Ex: text.split(', ') |
find() | Returns the index of the first occurrence of a substring (returns -1 if not found). Ex: text.find('gram') |
isalpha() | Returns True if the string contains only alphabetic characters (no spaces or punctuation).Ex: text.isalpha() |
isdigit() | Returns True if the string contains only digits, otherwise False .Ex: text.isdigit() |
startswith() | Checks if the string starts with the specified prefix. Ex: text.startswith('Hello') |
endswith() | Checks if the string ends with the specified suffix. Ex: text.endswith('!') |
count() | Counts the number of occurrences of a specified substring in the string. Ex: text.count('p') |
join() | Joins elements of an iterable (like a list) into a string, using the string as a separator. Ex: ' '.join(['Python', 'is', 'awesome']) |
capitalize() | Capitalizes the first character of the string and makes the rest lowercase. Ex: text.capitalize() |
title() | Converts the first character of each word in the string to uppercase. Ex: text.title() |
rjust() | Right-justifies the string, padding the left side with a specified character. Ex: text.rjust(20, '#') |
center() | Centers the string within a specified width, padding on both sides with the specified character. Ex: text.center(20, '*') |
String Methods in Python:
text = " Hello, World! "
# Example 1: strip()
print(text.strip()) # Removes leading and trailing whitespaces
# Output: "Hello, World!"
# Example 2: lower()
print(text.lower()) # Converts all characters to lowercase
# Output: " hello, world! "
# Example 3: upper()
print(text.upper()) # Converts all characters to uppercase
# Output: " HELLO, WORLD! "
# Example 4: replace()
print(text.replace('World', 'Python')) # Replaces 'World' with 'Python'
# Output: " Hello, Python! "
# Example 5: split()
text_to_split = "apple, banana, cherry"
print(text_to_split.split(', ')) # Splits the string into a list of substrings
# Output: ['apple', 'banana', 'cherry']
# Example 6: find()
print(text.find('gram')) # Returns the index of the first occurrence of 'gram'
# Output: -1 (because 'gram' is not in the string)
# Example 7: isalpha()
print(text.isalpha()) # Returns True if the string contains only alphabetic characters
# Output: False (because of spaces and punctuation)
# Example 8: isdigit()
text_digit = "12345"
print(text_digit.isdigit()) # Returns True if the string contains only digits
# Output: True
# Example 9: startswith()
print(text.startswith(' Hello')) # Returns True if the string starts with 'Hello'
# Output: True
# Example 10: endswith()
print(text.endswith('! ')) # Returns True if the string ends with '!'
# Output: True
# Example 11: count()
print(text.count('o')) # Returns the number of occurrences of 'o' in the string
# Output: 2
# Example 12: join()
words = ['Python', 'is', 'awesome']
print(' '.join(words)) # Joins list elements into a string with spaces
# Output: "Python is awesome"
# Example 13: capitalize()
text_to_capitalize = "hello"
print(text_to_capitalize.capitalize()) # Capitalizes the first character of the string
# Output: "Hello"
# Example 14: title()
text_to_title = "hello world"
print(text_to_title.title()) # Converts the first letter of each word to uppercase
# Output: "Hello World"
# Example 15: rjust()
text_rjust = "Python"
print(text_rjust.rjust(20, '#')) # Right-justifies the string within 20 characters, padding with '#'
# Output: "###############Python"
# Example 16: center()
text_center = "Python"
print(text_center.center(20, '*')) # Centers the string within 20 characters, padding with '*'
# Output: "******Python*******"
text = " Hello, World! "
# Example 1: strip()
print(text.strip()) # Removes leading and trailing whitespaces
# Output: "Hello, World!"
# Example 2: lower()
print(text.lower()) # Converts all characters to lowercase
# Output: " hello, world! "
# Example 3: upper()
print(text.upper()) # Converts all characters to uppercase
# Output: " HELLO, WORLD! "
# Example 4: replace()
print(text.replace('World', 'Python')) # Replaces 'World' with 'Python'
# Output: " Hello, Python! "
# Example 5: split()
text_to_split = "apple, banana, cherry"
print(text_to_split.split(', ')) # Splits the string into a list of substrings
# Output: ['apple', 'banana', 'cherry']
# Example 6: find()
print(text.find('gram')) # Returns the index of the first occurrence of 'gram'
# Output: -1 (because 'gram' is not in the string)
# Example 7: isalpha()
print(text.isalpha()) # Returns True if the string contains only alphabetic characters
# Output: False (because of spaces and punctuation)
# Example 8: isdigit()
text_digit = "12345"
print(text_digit.isdigit()) # Returns True if the string contains only digits
# Output: True
# Example 9: startswith()
print(text.startswith(' Hello')) # Returns True if the string starts with 'Hello'
# Output: True
# Example 10: endswith()
print(text.endswith('! ')) # Returns True if the string ends with '!'
# Output: True
# Example 11: count()
print(text.count('o')) # Returns the number of occurrences of 'o' in the string
# Output: 2
# Example 12: join()
words = ['Python', 'is', 'awesome']
print(' '.join(words)) # Joins list elements into a string with spaces
# Output: "Python is awesome"
# Example 13: capitalize()
text_to_capitalize = "hello"
print(text_to_capitalize.capitalize()) # Capitalizes the first character of the string
# Output: "Hello"
# Example 14: title()
text_to_title = "hello world"
print(text_to_title.title()) # Converts the first letter of each word to uppercase
# Output: "Hello World"
# Example 15: rjust()
text_rjust = "Python"
print(text_rjust.rjust(20, '#')) # Right-justifies the string within 20 characters, padding with '#'
# Output: "###############Python"
# Example 16: center()
text_center = "Python"
print(text_center.center(20, '*')) # Centers the string within 20 characters, padding with '*'
# Output: "******Python*******"
Frequently Asked Questions
What are Python string methods?
What are Python string methods?
Python string methods are built-in functions that allow you to perform various operations on strings, such as changing case, finding substrings, splitting, and more.
How do I convert a string to uppercase in Python?
How do I convert a string to uppercase in Python?
You can convert a string to uppercase in Python using the .upper() method. Example: 'hello'.upper() returns 'HELLO'.
How do I check if a string contains a substring in Python?
How do I check if a string contains a substring in Python?
To check if a string contains a substring, you can use the 'in' keyword. Example: 'hello' in 'hello world' returns True.
How do I split a string into a list in Python?
How do I split a string into a list in Python?
You can split a string into a list using the .split() method. Example: 'a,b,c'.split(',') returns ['a', 'b', 'c'].
How do I join a list into a string in Python?
How do I join a list into a string in Python?
You can join a list into a string using the .join() method. Example: ','.join(['a', 'b', 'c']) returns 'a,b,c'.
What's Next?
Next, you'll dive into Python keywords, which are reserved words that have special meanings in Python. You'll learn what each keyword does, how they help define the structure and flow of your programs, and why they cannot be used as variable names or identifiers.