Python String
In Python, strings are sequences of characters used to represent text. They are widely used in programming and essential for handling textual data. Strings are sequences of characters enclosed in either single quotes (‘’) or double quotes (“”). They are one of the most commonly used data types, and Python provides many useful methods to manipulate and work with strings.
1. Creating a Simple String with a Value
In Python, you can create strings by enclosing the text in either single (‘…’) or double (“…”) quotes.
Name = “Justin”
2. Getting the Number of Characters in the String
You can use the len() function to get the length of the string.
size = len(Name)
print(size) #
4. Joining Strings Using f-String Interpolation
In Python, you can use f-strings (formatted string literals) to embed variables in a string.
firstname = “Justin”
lastname = “bieber”
print(f”{firstname} {lastname}”) # Output: Justin bieber
Note: In step 3 for concatenation, we have used print(firstname + ” ” + lastname)
In step 4 for f-string we have used, print(f”{firstname} {lastname}”)
Both have given output as Justin bieber. i.e in f-string we can print the value the
way it has defined under the print command
Example:
firstname = “Justin”
lastname = “bieber”
print(f”{firstname} @ {lastname}”) # Output: Justin @ bieber
5. Joining Strings Using format()
You can also use the format() method to join strings using placeholders.
firstname = “Justin”
middlename = “hudson”
lastname = “bieber”
print(“{0} {1}”.format(firstname, lastname)) #Output: Justin bieber
print(“{0} {1} {2}”.format(firstname, middlename, lastname))
# Output: Justin hudson bieber
print(“{2} {1} {0}”.format(firstname, middlename, lastname))
# Output: bieber hudson Justin
As you can see the line below:
print(“{2} {1} {0}”.format(firstname, middlename, lastname))
placeholder {2} = lastname,
placeholder {1} = middlename,
placeholder {0} = firstname,
#Output: bieber hudson Justin
Even if the sequence changes, the value will remain the same in the index of placeholder.
6. Convert String to Uppercase
You can convert all characters in a string to uppercase using upper().
Name = “Justin”
Capital = Name.upper()
print(Capital) #
7. Convert String to Lowercase
To convert all characters in a string to lowercase, use lower()
Name = “Justin”
lowercase = Name.lower()
print(lowercase) # Output: justin
8. Retrieve a Substring from a String
You can extract a substring using slicing.
Name = “Justin”
substring = Name[0:4]
print(substring)
In the above example it will only print the first four characters from index 0-3.
Note: character on index 4 will not be included as it is 5th on position.
9. Remove Leading and Trailing Whitespace
To remove whitespace from the start and end of a string, use the strip() method.
Name = ” Justin drake “
space = Name.strip()
print(space) # Output: Justin drake
10. Check if a String Contains a Substring
Use the in keyword to check if a string contains a specific substring.
Name = “Justin drake”
shortname = “Justin” in Name
print(shortname) # Output: True
11. Check if a String Starts or Ends with a Substring
startswith() checks if a string starts with a specific substring.
endswith() checks if a string ends with a specific substring.
starting = Name.startswith(“Ju”)
print(starting) # Output: True
ending = Name.endswith(“!”)
print(ending) # Output: False
12. Compare Two Strings Using ==
In Python, you can compare two strings using the == operator.
Name = “Justin”
value = Name == “Hello, World!”
print(value) # Output: False
13. Copying a String
In Python, strings are immutable, so copying is as simple as assigning the value to a new variable.
Name = “Justin”
duplicate = Name
print(duplicate) # Output: Justin
14. Replacing Substrings in a String
You can replace parts of a string using the replace() method.
Name = “Justin bieber”
changeword = Name.replace(“Justin”, “Drake”)
changecharacter = Name.replace(“b”, “B”)
print(changeword) # Output: Drake bieber
print(changecharacter) # Output: Justin BieBer
15. Inserting Substrings
Python does not have an insert() method for strings, but you can concatenate substrings to simulate insertion.
Name = “Justin”
newName = Name[:6] + ” bieber” # Inserting at index 6
print(newName) # Output: Justin bieber
16. Removing Substrings
You can remove parts of a string using slicing or the replace() method.
Name = “Justin drake”
shortened = Name[:5] # remove the characters from 5th index
print(shortened) # Output: Justi
As, we have not mentioned anything before ‘:’ in shortened = Name[:5] it will
automatically start cropping the string from 0 index
Task:
1. Create a Simple String: Create a string variable called myName and assign it your name. Print the string to the console.
2. Get Length of String: Write a program to get the number of characters in the string myName and print the length.
3. Concatenation: Create two string variables firstName and lastName with your first and last names. Concatenate them using the + operator and print the result. Repeat the above step using string interpolation. Repeat the above step using placeholders.
4. Case Conversion: Convert the string myName to uppercase and print the result. Convert the string myName to lowercase and print the result.
5. Substring: Extract a substring from myName that includes the first three characters and print it. Extract the last three characters of myName and print them.
6. Trim: Create a string with leading and trailing white spaces and print it. Then, remove the white spaces using the Trim method and print the result.
7. Contains: Check if the string myName contains a specified substring (e.g., your first name) and print the result.
StartsWith and EndsWith: Check if the string myName starts with your first name and print the result. Check if the string myName ends with your last name and print the result.
8. Equals: Create another string variable with the same value as myName and check if they are equal using the Equals method. Print the result.
9. Copy: Copy the value of myName into another string variable called copiedName and print it.
10. Replace: Replace your first name in the string myName with another name and print the result. Replace all occurrences of a specific character in myName with another character and print the result.
11. Insert: Insert a middle name into the string myName at the appropriate position and print the result.
12. Remove: Remove the last name from the string myName and print the result.