Python String Basics
A string is a collection of alphabets, words, or other symbols. In Python, string literals can be created by enclosing characters in single, double, and triple quotes (but these are commonly used to represent multiline strings and docstrings). To create a multiline string, enclose the text in triple quotes ( """ or '''). Long lines can be split across multiple lines by adding a backslash ("\") at the end of each string.
Python strings are immutable and, once created, cannot be changed. Strings management functions always make a new line instead of modifying an existing one. Python provides essential functions for finding, concatenating, reversing, splitting, and comparing strings. Characters in a string can be accessed using the zero-based syntax .
Regular strings are an array of 8-bit ASCII bytes. When you declare a string in Python using single or double quotes, it creates a regular string by default, which only supports ASCII characters. Unicode strings are an array of 16-bit ASCII bytes and can support many more characters than standard strings, such as Chinese characters. Python 3 uses Unicode strings by default. In Python 2, you must start Unicode strings with the "u" character.
my_string = '"Double quotes" example' print(my_string) # output: "Double quotes" example
my_string = 'Backslash\r\nExample' print(my_string) # output: Backslash # output: Example
my_string = 'Line 1'\ 'Line 2'\ 'Line 3' print(my_string) # output: Line 1Line 2Line 3
my_string = """Line 1 Line 2 Line 3""" print(my_string) # output: Line 1 # output: Line 2 # output: Line 3
How to loop through each character in a string in Python?
We need to work with individual characters in the string. For this, we can use a 'for' loop. It iterates through an object (in our case, a string) from the first element to the last.
str = 'String' for s in str: print(s) # S # t # r # i # n # g
In this example, the for loop iterates over the str object and prints each character to the console.
How to reverse a string using the Python Slicing operator?
Using [::], you can cut off some substring from the string. But if you specify -1 as the last number, then Python will take action in the reverse order. And if you don't provide the first two elements, then Python will process the entire string. Thus, by using [::-1] operator, you can reverse the string.
print('Hello world'[::-1]) # output: dlrow olleH
How to reverse a string using join() and reversed() methods?
You can use the reversed() method to get the characters in a string in reverse order.
a = 'String' for symbol in reversed(a): print(symbol) # g # n # i # r # t # S
Now, to get a string from this array, we can use the join() method. When applied to a string array, it concatenates the elements of the array using the supplied string separator.
print(",".join(['One', 'Two', 'Three'])) # One,Two,Three
When used together, reversed() and join() can reverse the string.
print("".join(reversed("Hello World"))) # output: dlroW olleH
How to reverse a string using recursion?
def reverse_str(a: str) -> str: if not a: return "" return a[-1] + reverse_str(a[0:-1]) print(reverse_str('Hello World')) # output: dlroW olleH
The reverse_str function works as follows: it copies the last character of the string to the beginning by calling a[-1] and recursively calls itself again passing the string without the last character by calling a[0: -1]. There are many ways to reverse a string using recursion. The provided method is one of them.
How to reverse a string using a for loop in Python?
a = 'Hello World' b = '' for symbol in a: b = symbol + b a = b print(a) # output: dlroW olleH
In this method, we create an empty string "b", iterate over the characters in the original string "a", and add those characters to the beginning of the string "b", thus reversing the original string.
While Python does not have a built-in function to reverse a string, there are several ways to do it with just a few lines of code. You can use Slicing, a bunch of join() and reversed() methods, reverse a string using a recursive function, or use a for loop.