Module: M2-R5: Web Design & Publishing
Chapter: Ch1 Computer Intro
In Python, strings are sequences of characters enclosed within single, double, or triple quotes. Strings are one of the most commonly used data types and support a wide range of operations such as indexing, slicing, concatenation, repetition, and other useful methods.
Each character in a string has an index. Indexing starts from 0 for the first character and goes up to n-1. Negative indices count from the end, starting at -1.
text = "Python"
print(text[0]) # P
print(text[-1]) # n
Slicing extracts a portion of a string using the syntax string[start:end:step].
text = "PythonProgramming"
print(text[0:6]) # Python
print(text[6:]) # Programming
print(text[:6]) # Python
print(text[::2]) # PtoPormig
You can join strings together using concatenation with + and repeat them with *.
a = "Hello"
b = "World"
print(a + " " + b) # Hello World
print(a * 3) # HelloHelloHello
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[0:4]) # Pyth
print(word[::2]) # Pto
a = "Hi"
b = "There"
print(a + " " + b) # Hi There
print(a * 4) # HiHiHiHi
text = " Python Programming "
print(len(text)) # 23
print(text.strip()) # Python Programming
print(text.upper()) # PYTHON PROGRAMMING
print(text.replace("Python", "Java")) # Java Programming
print("Python" in text) # True
+ and *.