Strings In Python
In Python, a string is a sequence of characters enclosed within either single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). Strings are used to represent text data and are one of the fundamental data types in the language. Here are some key points about strings in Python:
String Creation: You can create strings using single quotes, double quotes, or triple quotes:
pythonCopy codesingle_quoted = 'This is a single-quoted string.' double_quoted = "This is a double-quoted string." triple_single_quoted = '''This is a triple-quoted string that can span multiple lines.''' triple_double_quoted = """This is also a triple-quoted string that can span multiple lines."""
Accessing Characters: You can access individual characters within a string using indexing:
pythonCopy codemy_string = "Hello, World!" print(my_string[0]) # Output: 'H' print(my_string[7]) # Output: 'W'
String Slicing: You can extract substrings using slicing:
pythonCopy codemy_string = "Hello, World!" print(my_string[0:5]) # Output: 'Hello' print(my_string[7:]) # Output: 'World!'
String Concatenation: You can concatenate strings using the
+
operator:pythonCopy codestr1 = "Hello" str2 = "World" combined = str1 + " " + str2 # Output: 'Hello World'
String Methods: Python provides various built-in methods to manipulate strings, such as
upper()
,lower()
,strip()
,replace()
,split()
, and more:pythonCopy codemy_string = " Hello, World! " print(my_string.strip()) # Output: 'Hello, World!' print(my_string.lower()) # Output: ' hello, world! ' print(my_string.replace('!', '?')) # Output: ' Hello, World? '
String Formatting: You can format strings using the
.format()
method or f-strings (formatted string literals):pythonCopy codename = "Alice" age = 30 formatted_string = "My name is {} and I am {} years old.".format(name, age) f_string = f"My name is {name} and I am {age} years old."
String Length: You can find the length of a string using the
len()
function:pythonCopy codemy_string = "Hello, World!" length = len(my_string) # Output: 13
Escape Characters: You can use escape characters like
\n
(newline),\t
(tab),\\
(backslash), etc., within strings.pythonCopy codeescaped_string = "This is a line\nwith a newline character."
Remember that strings in Python are immutable, meaning their values cannot be changed after creation. If you need to modify a string, you create a new one with the desired modifications.