In Python programming, a string is a sequence of characters enclosed within single or double quotes. Strings are immutable, meaning they cannot be changed once created. Python provides a lot of built-in functions and methods for string manipulation, making it easy to work with strings.
In this post, I have added some simple examples and exercises for using strings in Python for various needs. Check out these examples to get a clear idea of how string manipulation works in Python.
Let’s dive right in.
1. Creating a string in Python
myString = "Hello, Python!"
print(myString)
Output:
2. Accessing characters in a string
myString = "Hello, Python!"
print("First character:", myString[0])
print("Fifth character:", myString[4])
Output:
3. String slicing
myString = "Hello, Python!"
slicedString = myString[0:5]
print("Sliced string:", slicedString)
Output:
4. Concatenating strings
stringOne = "Hello"
stringTwo = "Python"
concatenatedString = stringOne + " " + stringTwo
print("Concatenated string:", concatenatedString)
Output:
5. Repeating strings
myString = "Hello "
repeatedString = myString * 3
print("Repeated string:", repeatedString)
Output:
6. Finding the length of a string
myString = "Hello, Python!"
stringLength = len(myString)
print("Length of string:", stringLength)
Output:
7. Converting a string to uppercase
myString = "Hello, Python!"
upperString = myString.upper()
print("Uppercase string:", upperString)
Output:
8. Converting a string to lowercase
myString = "Hello, Python!"
lowerString = myString.lower()
print("Lowercase string:", lowerString)
Output:
9. Replacing characters in a string
myString = "Hello, Python!"
replacedString = myString.replace("Python", "World")
print("Replaced string:", replacedString)
Output:
10. Splitting a string
myString = "Hello, Python! How are you?"
splittedString = myString.split(" ")
print("Splitted string:", splittedString)
Output:
11. Joining a list of strings
myList = ["Hello", "Python", "World"]
joinedString = " ".join(myList)
print("Joined string:", joinedString)
Output:
12. Counting the occurrences of a character in a string
myString = "Hello, Python!"
count = myString.count("l")
print("Number of occurrences of 'l':", count)
Output:
13. Finding the index of a character in a string
myString = "Hello, Python!"
index = myString.index("P")
print("Index of character 'P':", index)
Output:
14. Checking if a string starts with a specific substring
myString = "Hello, Python!"
startsWith = myString.startswith("Hello")
print("Does the string start with 'Hello'? :", startsWith)
Output:
15. Checking if a string ends with a specific substring
myString = "Hello, Python!"
endsWith = myString.endswith("Python!")
print("Does the string end with 'Python!'? :", endsWith)
Output:
I hope this article was helpful. Check out my post on 10 Python Set Exercises and Examples.