Approx. read time: 3.6 min.
Post: Python Basic String Operations
Python Basic String Operations Tutorial
In this tutorial, we will explore the basics of string operations in Python. Strings are sequences of characters enclosed within quotes. Python allows you to perform various operations on strings, such as slicing, indexing, and formatting.
Defining Strings
Strings can be defined using single or double quotes:
astring = "Hello world!" astring2 = 'Hello world!' print(astring) print(astring2)
Explanation
astring
andastring2
are defined as strings using double and single quotes, respectively.- The
print
function outputs the strings to the console.
You can run the above code using the Trinket.io online Python compiler to see the output.
Printing and String Length
The len()
function returns the length of a string, including spaces and punctuation:
astring = "Hello world!" print("Length of astring:", len(astring))
Explanation
len(astring)
returns the length ofastring
, which is 12 characters long.
Indexing and Finding Substrings
The index()
method finds the first occurrence of a substring:
astring = "Hello world!" print("Index of 'o':", astring.index("o"))
Explanation
astring.index("o")
returns 4 because the first “o” is at index 4.- Python uses 0-based indexing, so counting starts from 0.
Counting Occurrences of a Character
The count()
method counts the number of occurrences of a substring:
astring = "Hello world!" print("Count of 'l':", astring.count("l"))
Explanation
astring.count("l")
returns 3 because “l” appears three times inastring
.
Slicing Strings
Slicing allows you to extract parts of a string using the [start:stop:step]
syntax:
astring = "Hello world!" print("Slice astring[3:7]:", astring[3:7]) print("Slice astring[3:7:2]:", astring[3:7:2])
Explanation
astring[3:7]
returns “lo w”, which includes characters from index 3 to 6.astring[3:7:2]
returns “l “, which includes every second character from index 3 to 6.
Reversing a String
You can reverse a string using slicing:
astring = "Hello world!" print("Reversed string:", astring[::-1])
Explanation
astring[::-1]
returns “!dlrow olleH”, which is the reversed string.
Converting to Uppercase and Lowercase
The upper()
and lower()
methods convert strings to uppercase and lowercase, respectively:
astring = "Hello world!" print("Uppercase:", astring.upper()) print("Lowercase:", astring.lower())
Explanation
astring.upper()
returns “HELLO WORLD!”.astring.lower()
returns “hello world!”.
Checking String Start and End
The startswith()
and endswith()
methods check if a string starts or ends with a specific substring:
astring = "Hello world!" print("Starts with 'Hello':", astring.startswith("Hello")) print("Ends with 'asdfasdfasdf':", astring.endswith("asdfasdfasdf"))
Explanation
astring.startswith("Hello")
returnsTrue
.astring.endswith("asdfasdfasdf")
returnsFalse
.
Splitting Strings
The split()
method splits a string into a list of substrings based on a delimiter:
astring = "Hello world!" afewwords = astring.split(" ") print("Splitted list:", afewwords)
Explanation
astring.split(" ")
splitsastring
into a list['Hello', 'world!']
.
Exercise: Fix the Code
Try to fix the code to print out the correct information by changing the string s
.
s = "Strings are awesome!" # Length should be 20. above text is 20 characters. print("Length of s = %d" % len(s)) # First occurrence of "a" should be at index 8 print("The first occurrence of the letter a = %d" % s.index("a")) # Number of a's should be 2 print("a occurs %d times" % s.count("a")) # Slicing the string into bits print("The first five characters are '%s'" % s[:5]) # Start to 5 print("The next five characters are '%s'" % s[5:10]) # 5 to 10 print("The thirteenth character is '%s'" % s[12]) # Just number 12 print("The characters with odd index are '%s'" % s[1::2]) # (0-based indexing) print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end # Convert everything to uppercase print("String in uppercase: %s" % s.upper()) # Convert everything to lowercase print("String in lowercase: %s" % s.lower())
Explanation
- The
len()
function calculates the length of the string. - The
index()
method finds the first occurrence of a substring. - The
count()
method counts the occurrences of a substring. - Slicing extracts specific parts of the string.
- The
upper()
andlower()
methods convert the string to uppercase and lowercase, respectively.
You can use the Trinket.io online Python compiler to run and test the above code snippets.
By understanding and practicing these basic string operations, you can manipulate and work with strings effectively in Python.