Python String
In Python, a string is a sequence of characters enclosed in quotes. It can include letters, numbers,
symbols or spaces. Since Python has no separate character type, even a single character is treated as
a string with length one. Strings are widely used for text handling and manipulation.
Creating a String
Strings can be created using either single ('...') or double ("...") quotes. Both behave the same.
Example: Creating two equivalent strings one with single and other with double quotes.
s1 = 'GfG' # single quote
s2 = "GfG" # double quote
print(s1)
print(s2)
Output
GfG
GfG
Multi-line Strings
Use triple quotes ('''...''' ) or ( """...""") for strings that span multiple lines. Newlines are preserved.
Example: Define and print multi-line strings using both styles.
Accessing characters in String
Strings are indexed sequences. Positive indices start at 0 from the left; negative indices start at -
1 from the right as represented in below image:
Example 1: Access specific characters through positive indexing.
s = "GeeksforGeeks"
print(s[0]) # first character
print(s[4]) # 5th character
String Slicing
Slicing is a way to extract a portion of a string by specifying the start and end indexes. The syntax for
slicing is string[start:end], where start starting index and end is stopping index (excluded).
Example: In this example we are slicing through range and reversing a string.