A string is an ordered sequence of characters enclosed in quotes. It can hold letters, digits, symbols, and spaces. Python has no dedicated character type, so a single character is just a string of length one. Strings are mainly used to store and process text.
Creating Strings
Single and double quotes work identically.
a = 'Cxai'
b = "Codeexai"
print(a)
print(b)Output:
Cxai
CodeexaiMulti-line Strings
Wrap text in triple single or triple double quotes to span several lines. Line breaks are kept as written.
s = """I am Learning
Python String on Codeexai"""
print(s)
s = '''I'm
John'''
print(s)Output:
I am Learning
Python String on Codeexai
I'm
JohnAccessing Characters
Each character has a position. Counting from the left starts at 0, and counting from the right starts at -1.
Positive indexing:
s = "ABCDEF"
print(s[0])
print(s[4])Output:
A
ENote: An index beyond the string's length raises an IndexError. Indices must be integers; a float or other type raises a TypeError.
Negative indexing:
s = "ABCDEF"
print(s[-3])
print(s[-5])Output:
D
BSlicing
Slicing pulls out part of a string using string[start:end]. The character at start is included; the one at end is not.
s = "ABCDEF"
print(s[1:4])
print(s[:3])
print(s[3:])
print(s[::-1])Output:
BCD
ABC
DEF
FEDCBALooping Over a String
Since strings are iterable, a for loop visits one character at a time, in order.
s = "ABCDEF"
for char in s:
print(char)Output:
A
B
C
D
E
FImmutability
A string cannot be modified once created. Any change produces a new string and leaves the original untouched.
s = "aBCDEF"
s = "A" + s[1:]
print(s)Output:
ABCDEFHere, "aBCDEF" is not altered. A new string is built by joining "A" with everything from index 1 onward.
Deleting a String
Individual characters can't be removed, but the whole variable can be deleted with del.
s = "ABC"
del sNote: Using the variable afterward raises a NameError, because it no longer exists.
Updating a String
Because strings can't be edited in place, updates are done by creating a new string through slicing or methods such as replace().
s = "ABCD EF"
s1 = "H" + s[1:]
s2 = s.replace("ABC", "abc")
print(s1)
print(s2)Output:
HBCD EF
abcD EFs1: takes everything from index 1 and puts"H"in front.s2:replace("ABC", "abc")returns a new string with the substitution.
Common String Methods
1. len(): returns the number of characters, counting spaces and punctuation.
s = "Codeexai"
print(len(s))Output:
82. upper() and lower(): convert all characters to uppercase or lowercase.
s = "Hello World"
print(s.upper())
print(s.lower())Output:
HELLO WORLD
hello world3. strip() and replace(): strip() trims whitespace from both ends; replace() swaps every occurrence of a substring for another.
s = " ABC "
print(s.strip())
s = "Python is fun"
print(s.replace("fun", "awesome"))Output:
ABC
Python is awesomeConcatenation and Repetition
Concatenation: join strings with +.
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)Output:
Hello WorldRepetition: multiply a string with * to repeat it.
s = "Hello "
print(s * 3)Output:
Hello Hello Hello