Strings in Python
Strings in Python
print(len(txt))
Slicing
You can return a range of characters by using the slice syntax.
b = "Hello, World!"
print(b[:5])
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
b = "Hello, World!"
print(b[-5:-2])
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very
often you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the
end:
a = "Hello, World!"
print(a.replace("H", "J"))
The split() method returns a list where the text between the
specified separator becomes the list items.
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']