A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.
Pythons="GfG"print(s[1])# access 2nd chars1=s+s[0]# updateprint(s1)# print
In this example,s holds the value "GfG" and is defined as a string.
Creating a String
Strings can be created using eithersingle (')or double (")quotes.
Pythons1='GfG's2="GfG"print(s1)print(s2)
Multi-line Strings
If we need a string to span multiple lines then we can usetriple quotes (''' or """).
Pythons="""I am LearningPython String on GeeksforGeeks"""print(s)s='''I'm aGeek'''print(s)
OutputI am LearningPython String on GeeksforGeeksI'm a Geek
Accessing characters in Python String
Strings in Python are sequences of characters, so we can access individual characters usingindexing. Strings are indexed starting from0and-1 from end. This allows us to retrieve specific characters from the string.
Python String syntax indexingPythons="GeeksforGeeks"# Accesses first character: 'G'print(s[0])# Accesses 5th character: 's'print(s[4])
Note:Accessing an index out of range will cause anIndexError. Only integers are allowed as indices and using a float or other types will result in aTypeError.
Python allows negative address references to access characters from back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
Pythons="GeeksforGeeks"# Accesses 3rd character: 'k'print(s[-10])# Accesses 5th character from end: 'G'print(s[-5])
String Slicing
Slicingis a way to extract portion of a string by specifying thestartandendindexes. The syntax for slicing isstring[start:end], wherestartstarting index andendis stopping index (excluded).
Pythons="GeeksforGeeks"# Retrieves characters from index 1 to 3: 'eek'print(s[1:4])# Retrieves characters from beginning to index 2: 'Gee'print(s[:3])# Retrieves characters from index 3 to the end: 'ksforGeeks'print(s[3:])# Reverse a stringprint(s[::-1])
OutputeekGeeksforGeeksskeeGrofskeeG
String Immutability
Strings in Python are immutable. This means that they cannot be changed after they are created. If we need to manipulate strings then we can use methods likeconcatenation, slicing,orformatting to create new strings based on the original.
Pythons="geeksforGeeks"# Trying to change the first character raises an error# s[0] = 'I' # Uncommenting this line will cause a TypeError# Instead, create a new strings="G"+s[1:]print(s)
Deleting a String
In Python, it is not possible to delete individual characters from a string since strings are immutable. However, we can delete an entire string variable using thedelkeyword.
Pythons="GfG"# Deletes entire stringdels
Note:After deleting the string usingdeland if we try to accesss then it will result in aNameError because the variable no longer exists.
Updating a String
To update a part of a string we need to create a new string since strings are immutable.
Pythons="hello geeks"# Updating by creating a new strings1="H"+s[1:]# replacnig "geeks" with "GeeksforGeeks"s2=s.replace("geeks","GeeksforGeeks")print(s1)print(s2)
OutputHello geekshello GeeksforGeeks
Explanation:
- For s1,The original strings is sliced from index 1 to end of string and then concatenate "H" to create a new strings1.
- For s2, we can created a new string s2 and usedreplace() method to replace 'geeks' with 'GeeksforGeeks'.
Common String Methods
Python provides a various built-in methods to manipulate strings. Below are some of the most useful methods.
len(): Thelen() function returns the total number of characters in a string.
Pythons="GeeksforGeeks"print(len(s))# output: 13
upper() and lower():upper() method converts all characters to uppercase.lower()method converts all characters to lowercase.
Pythons="Hello World"print(s.upper())# output: HELLO WORLDprint(s.lower())# output: hello world
OutputHELLO WORLDhello world
strip() and replace():strip() removes leading and trailing whitespace from the string andreplace(old, new)replaces all occurrences of a specified substring with another.
Pythons=" Gfg "# Removes spaces from both endsprint(s.strip())s="Python is fun"# Replaces 'fun' with 'awesome'print(s.replace("fun","awesome"))
OutputGfgPython is awesome
To learn more about string methods, please refer toPython String Methods.
Concatenating and Repeating Strings
We can concatenate strings using+ operatorand repeat them using* operator.
Strings can be combined by using+ operator.
Pythons1="Hello"s2="World"s3=s1+" "+s2print(s3)
We can repeat a string multiple times using* operator.
Python
Formatting Strings
Python provides several ways to include variables inside strings.
Using f-strings
The simplest and most preferred way to format strings is by usingf-strings.
Pythonname="Alice"age=22print(f"Name:{name}, Age:{age}")
OutputName: Alice, Age: 22
Using format()
Another way to format strings is by usingformat()method.
Pythons="My name is{} and I am{} years old.".format("Alice",22)print(s)
OutputMy name is Alice and I am 22 years old.
Usingin for String Membership Testing
Theinkeywordchecks if a particular substring is present in a string.
Pythons="GeeksforGeeks"print("Geeks"ins)print("GfG"ins)
Quiz:
Related Articles:
Recommended Problems:

Python String

String Operations in Python [Part -1]

String Operations in Python [Part -2]