Python Strings
1. Creating Strings:
Strings can be created using single quotes ('
), double quotes ("
), or triple quotes
('''
or """
).
single_quoted = 'Hello, World!'
double_quoted = "Python is awesome!"
triple_quoted = '''This is a
multiline string.'''
2. Accessing Characters:
Individual characters in a string can be accessed using indexing.
message = "Hello, World!"
first_char = message[0] # 'H'
3. String Slicing:
You can extract a substring from a string using slicing.
message = "Hello, World!"
substring = message[7:12] # 'World'
4. String Concatenation:
Strings can be concatenated using the +
operator.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # 'John Doe'
5. String Length:
The len()
function is used to get the length (number of characters) of a string.
message = "Hello, World!"
length = len(message) # 13
6. String Methods:
Python provides a variety of built-in string methods for string manipulation, such as upper()
,
lower()
, replace()
, find()
, split()
, and more.
text = "Python Programming"
uppercase_text = text.upper()
lowercase_text = text.lower()
replaced_text = text.replace("Python", "Java")
7. Escape Characters:
Escape characters are used to represent special characters in a string, such as newline (\n
), tab
(\t
), or a backslash (\\
).
multiline_text = "This is a\nmultiline\nstring."
8. String Formatting:
String formatting allows you to embed expressions inside string literals.
name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
9. Raw Strings:
Raw strings are created by prefixing the string literal with r
or R
. They are often
used for regular expressions or paths to avoid interpreting escape characters.
raw_string = r"C:\Users\John\Documents"
10. String Conversion:
You can convert other data types to strings using the str()
function.
num = 42
str_num = str(num) # Converts the integer 42 to the string '42'
Strings are versatile and are used in various contexts, such as text processing, input/output operations, and formatting. Familiarity with string manipulation and the available string methods is important for effective Python programming.