string
In Python, a string is a data type used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers. For example, the word "hello" or the phrase "hello world" are both strings. Even "12345" could be considered a string if it is specified correctly. In Python, string literals are enclosed by either single, double, or triple quotes:
Single quotes: 'allows single quote'
Double quotes: "allows double quote"
Triple quotes: ''' or """ are used to specify multi-line strings and also can be used for commenting out chunks of code or creating docstrings.
For example:
s = 'hello'
t = "hello, world!"
u = '''hello
world'''
v = """Hello,
World!"""
Common String Operations:
Concatenation: The process of combining two strings:
greeting = "Hello, " + "World!"
Multiplication: This involves creating multiple copies of a string:
laughter = "Ha" * 3 # results in HaHaHa
Accessing Characters: You can access individual characters in a string using indexing:
hello = "Hello"
print(hello[0]) # prints 'H'
Slicing: This allows you to access a range of characters in a string:
z = "Hello, World!"
print(z[2:5]) # output is 'llo'
Length: The len() function returns the length of a string:
txt = "Hello"
x = len(txt)
String Methods: Strings have a set of methods that allow you to manipulate the content. These are functions that perform actions on the string and return results. They don't change the original string, but return a new string or value. Examples include lower(), upper(), strip(), replace(), split(), etc.
Example:
txt = "hello world"
txt_upper = txt.upper() # returns "HELLO WORLD"
Formatting: Strings in Python can be formatted using the .format() method, f-strings (as of Python 3.6+), or using old-style % formatting.
Using .format():
text = "The {} sat on the mat.".format("cat")
Using f-strings:
animal = "cat"
text = f"The {animal} sat on the mat."
Escape Characters: To insert characters that are illegal in a string, you use an escape character. An escape character is a backslash \ followed by the character you want to insert.
Example:
txt = “We are so happy to see you here at \”Lokang\"." # The quote marks are escaped
Strings are immutable sequences, meaning they cannot be changed after they are created (items cannot be replaced or removed). Any operations on strings will thus result in new string objects being created.
Understanding string manipulation is essential in any programming language, but Python provides a particularly large array of methods to handle and operate on string data efficiently.