STRING
A string is a sequence of characters, and it is one of the fundamental data types. Strings are used to represent text and are enclosed in either single ('
) or double ("
) quotes. Here are some basic concepts and operations related to strings in Python:
Creating string
# Using single quotes
single_quoted_string = 'Hello, World!'
# Using double quotes
double_quoted_string = "Python is awesome."
# Using triple quotes for multiline strings
multiline_string = '''This is a
multiline
string.'''
Accessing character in string
text = "Python"
first_char = text[0] # Access the first character (indexing starts from 0)
last_char = text[-1] # Access the last character
substring = text[1:4] # Access a substring (slicing)
String concatenation
str1 = "Hello"
str2 = "World"
concatenated_string = str1 + ", " + str2 + "!"
print(concatenated_string)
# Output: Hello, World!
String methods
message = "python programming"
# Capitalize the first letter
capitalized = message.capitalize()
# Convert to uppercase
uppercase = message.upper()
# Find the index of a substring
index = message.find("python")
# Replace a substring
new_message = message.replace("programming", "is fun")
# Check if the string starts with a specific prefix
starts_with = message.startswith("python")
# Split the string into a list of words
word_list = message.split()
# Check if the string contains only alphanumeric characters
is_alphanumeric = message.isalnum()
String formatting
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: My name is Alice and I am 30 years old.
Escape characters
escaped_string = "This is a \"quote\" and this is a newline:\nNew line."
print(escaped_string)
# Output: This is a "quote" and this is a newline:
# New line.