Python Fundamentals: Strings
Python strings are sequences of characters. They are immutable, which means once a string is created, it cannot be changed. However, we can verify its contents, length, replace parts of the string, and much more.
a. Creating a string: Strings in Python can be created using single quotes, double quotes, or triple quotes.
b. Accessing characters in a string: We can access individual characters using indexing and a range of characters using slicing.
c. String operations: Python includes the following string operations - concatenation, repetition, membership, iteration.
d. String methods: Python includes the following built-in methods to manipulate strings - lower(), upper(), join(), split(), find(), replace() etc.
a. Creating a string: Strings in Python can be created using single quotes, double quotes, or triple quotes.
Code
str1 = 'Hello, World!' print(str1)
Output
Hello World!
b. Accessing characters in a string: We can access individual characters using indexing and a range of characters using slicing.
Code
str1 = 'Hello, World!' print(str1[0]) print(str1[2:5]) print(str1[:])
Output
H llo Hello, World!
c. String operations: Python includes the following string operations - concatenation, repetition, membership, iteration.
Code
str1 = 'Hello, World!' str2 = 'Python' print(str1 + " " + str2) print(str2 * 3) print('n' in str2)
Output
Hello, World! Python PythonPythonPython True
d. String methods: Python includes the following built-in methods to manipulate strings - lower(), upper(), join(), split(), find(), replace() etc.
Code
str1 = 'Hello, World!' str2 = 'Python' print(str2.lower()) print(str2.upper()) print(str1.split(',')) print(str2.find('t')) print(str2.replace('Python', 'Java'))
Output
python PYTHON ['Hello', ' World!'] 2 Java