Python Strings
Creating a string
In Python, you can create a string by enclosing characters in single or double quotes. For example:
string1 = 'This is a string' string2 = "This is also a string"
You can also use triple quotes to create a multi-line string:
string3 = '''This is a multi-line string''' string4 = """This is also a multi-line string"""
String Characteristics
Strings in Python are immutable, which means that you cannot change the characters in a string once it has been created. However, you can create a new string by concatenating (joining) two or more strings together. For example:
string1 = 'Hello' string2 = 'World' # Concatenate the strings string3 = string1 + ' ' + string2 print(string3) # Output: "Hello World"
You can also use the * operator to repeat a string a certain number of times:
string4 = 'Hello' * 3 print(string4) # Output: "HelloHelloHello"
Looping in strings
You can loop through the characters in a string using a for loop. For example:
string = 'Hello World'
for char in string:
print(char)
# Output:
# H
# e
# l
# l
# o
#
# W
# o
# r
# l
# d
You can also use the enumerate() function to loop through a string and get the index of each character:
string = 'Hello World'
for index, char in enumerate(string):
print(f'Character at index {index}: {char}')
# Output:
# Character at index 0: H
# Character at index 1: e
# Character at index 2: l
# Character at index 3: l
# Character at index 4: o
# Character at index 5:
# Character at index 6: W
# Character at index 7: o
# Character at index 8: r
# Character at index 9: l
# Character at index 10: d
String length
You can use the len() function to get the length of a string, which is the number of characters it contains. For example:
string = 'Hello World' string_length = len(string) print(string_length) # Output: 11
You can also use the len() function to get the length of a string when you are looping through it. For example:
string = 'Hello World'
for index, char in enumerate(string):
print(f'Character at index {index}: {char}')
if index == len(string) - 1:
print('This is the last character')
# Output:
# Character at index 0: H
# Character at index 1: e
# Character at index 2: l
# Character at index 3: l
# Character at index 4: o
