Menu
Python Strings
In Python, a string is a sequence of characters enclosed in single (‘) or double (“) quotes. Strings are used to represent text and are one of the fundamental data types. Here’s an overview of working with strings in Python:
Creating Strings:
# Single quotes
single_quoted = 'Hello, World!'
# Double quotes
double_quoted = "Python Programming"
Both single and double quotes are valid for creating strings. Choose one style and stick with it for consistency.
String Operations:
- Concatenation:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Outputs: John Doe
-
- Repetition:
greeting = "Hello, "
repeated_greeting = greeting * 3
print(repeated_greeting) # Outputs: Hello, Hello, Hello,
-
- Accessing Characters:
language = "Python"
first_letter = language[0] # Indexing starts at 0
print(first_letter) # Outputs: P
-
- Slicing:
phrase = "Python is fun!"
substring = phrase[7:9]
print(substring) # Outputs: is
-
- String Length:
message = "Hello, World!"
length = len(message)
print(length) # Outputs: 13
String Methods:
Python provides a variety of built-in string methods for common operations:
-
- Changing Case:
text = "Python Programming"
# Convert to lowercase
lowercase_text = text.lower()
# Convert to uppercase
uppercase_text = text.upper()
- Finding Substrings:
sentence = "Python is easy to learn."
# Find the index of a substring
index = sentence.find("easy") # Outputs: 10
-
- Replacing Text:
statement = "Python is fun."
# Replace "fun" with "awesome"
new_statement = statement.replace("fun", "awesome")
-
- Splitting Strings:
words = "Python is versatile."
# Split the string into a list of words
word_list = words.split()
String Formatting:
-
- Concatenation:
name = "Alice"
greeting = "Hello, " + name + "!"
-
- Formatted Strings (f-strings):
name = "Bob"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
-
- Format Method:
name = "Charlie"
age = 25
greeting = "Hello, {}! You are {} years old.".format(name, age)
Type Conversion:
You can convert between different data types using functions like
int()
, float()
, str()
, etc.
# Convert float to integer
x = int(5.9) # Outputs: 5
# Convert integer to float
y = float(42) # Outputs: 42.0
# Convert integer to complex
z = complex(3) # Outputs: (3+0j)
Understanding string operations and methods is essential for manipulating and working with text in Python. Strings are versatile and play a crucial role in various programming tasks, from simple text processing to complex data manipulations.