Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
Now Reading
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
In this tutorial, we will delve deep into various String Methods Python. Python provides a built-in class, str, which comes with several methods to manipulate and analyze strings. For professionals looking to upskill, understanding these methods is crucial for text processing, data cleaning, and other common tasks. Additionally, mastering these methods will enable you to handle textual data efficiently and lay a solid foundation for advanced topics like regular expressions and natural language processing.
String methods Python encompass a variety of functions. From modifying the case of the string, stripping whitespace, checking if the string starts or ends with a particular substring, to finding the index of a substring, and many more. We will explore string methods in Python with examples to provide a comprehensive understanding.
This tutorial is designed for those who already have a basic understanding of Python and want to deepen their knowledge of string manipulation techniques, which are fundamental skills for every Python developer.
Code:
original_string = "Hello, World!"
# Convert to uppercase
uppercase_string = original_string.upper()
print(uppercase_string) # Output: HELLO, WORLD!
# Convert to lowercase
lowercase_string = original_string.lower()
print(lowercase_string) # Output: hello, world!
# Convert to title case (capitalize the first letter of each word)
titlecase_string = original_string.title()
print(titlecase_string) # Output: Hello, World!
# Capitalize only the first letter of the string
capitalize_string = original_string.capitalize()
print(capitalize_string) # Output: Hello, world!
Method Description
str.upper() Converts all characters in the string to uppercase.
str.lower() Converts all characters in the string to lowercase.
str.title() Capitalizes the first letter of each word in the string.
str.capitalize() Capitalizes the first letter of the string.
str.strip() Removes leading and trailing whitespace characters.
str.lstrip() Removes leading whitespace characters.
str.rstrip() Removes trailing whitespace characters.
str.startswith(prefix) Checks if the string starts with the specified prefix.
str.endswith(suffix) Checks if the string ends with the specified suffix.
str.replace(old, new) Replaces occurrences of old with new in the string.
str.find(sub) Returns the index of the first occurrence of sub in the string, or -1 if
not found.
str.index(sub)Similar to find(), but raises an exception if sub is not found.
str.count(sub)Counts the number of non-overlapping occurrences of sub in the
string.
str.split()Splits the string into a list of substrings using whitespace as the
default separator.
str.split(sep)Splits the string into a list of substrings using sep as the separator.
str.join(iterable)Joins the elements of an iterable (e.g., a list) with the string as the
separator.
str.isdigit()Checks if the string consists only of digits.
str.isalpha()Checks if the string consists only of alphabetic characters.
str.isalnum()Checks if the string consists only of alphanumeric characters.
str.islower()Checks if all characters in the string are lowercase.
str.isupper()Checks if all characters in the string are uppercase.
Example:
Code:
# Original string
text = " Hello, World! "
# Convert to uppercase
uppercase_text = text.upper()
print(uppercase_text) # Output: " HELLO, WORLD! "
# Convert to lowercase
lowercase_text = text.lower()
print(lowercase_text) # Output: " hello, world! "
# Capitalize the first letter of each word
titlecase_text = text.title()
print(titlecase_text) # Output: " Hello, World! "
# Remove leading and trailing spaces
stripped_text = text.strip()
print(stripped_text) # Output: "Hello, World!"
# Check if the string starts with "Hello"
starts_with_hello = text.startswith("Hello")
print(starts_with_hello) # Output: False
# Check if the string ends with "World!"
ends_with_world = text.endswith("World!")
print(ends_with_world) # Output: False
# Replace "Hello" with "Hi"
replaced_text = text.replace("Hello", "Hi")
print(replaced_text) # Output: " Hi, World! "
# Split the string into a list of words
split_words = text.split()
print(split_words) # Output: ['Hello,', 'World!']
# Join the words in the list with a space as the separator
joined_text = ' '.join(split_words)
print(joined_text) # Output: "Hello, World!"
Code:
# Using format() method for string formatting
name = "Alice"
age = 30
# Basic string formatting
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Using positional placeholders
formatted_pos = "Name: {0}, Age: {1}".format(name, age)
print(formatted_pos)
# Using named placeholders
formatted_named = "Name: {n}, Age: {a}".format(n=name, a=age)
print(formatted_named)
# Combining positional and named placeholders
combined_formatted = "Name: {}, Age: {a}".format(name, a=age)
print(combined_formatted)
# Formatting with different data types
pi = 3.14159
formatted_float = "The value of pi is {:.2f}".format(pi)
print(formatted_float)
# Formatting using index and value from a tuple
person = ("Bob", 25)
formatted_tuple = "Name: {0[0]}, Age: {0[1]}".format(person)
print(formatted_tuple)
Explanation:
In this example:
Code:
# Using single quotes
single_quoted_string = 'Hello, World!'
print(single_quoted_string)
# Using double quotes
double_quoted_string = "Hello, World!"
print(double_quoted_string)
# Using triple quotes for multiline strings
multiline_string = '''This is a
multiline
string.'''
print(multiline_string)
# Escaping special characters
escaped_string = "She said, \"Hello!\""
print(escaped_string)
# Concatenating strings
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Explanation:
In the above example:
Code:
# Indexing strings
my_string = "Hello, World!"
# Accessing individual characters using indexing
first_char = my_string[0]
second_char = my_string[7]
last_char = my_string[-1] # Negative index counts from the end
print("First char:", first_char)
print("Second char:", second_char)
print("Last char:", last_char)
# Slicing strings to get substrings
substring = my_string[7:12]
print("Substring:", substring) # Output: "World"
# Splitting strings
sentence = "Python is a powerful programming language."
words = sentence.split() # Split using whitespace by default
print("Words:", words)
# Splitting with a specified delimiter
csv_data = "Alice,30,Engineer"
csv_values = csv_data.split(",")
print("CSV values:", csv_values)
Explanation:
In this code:
Code:
# Original string
original_string = "Hello, World!"
# Reassigning a string variable
modified_string = original_string.replace("Hello", "Hi")
print("Original:", original_string)
print("Modified:", modified_string)
# Reassigning with concatenation
greeting = "Hi"
name = "Alice"
full_greeting = greeting + ", " + name + "!"
print("Full Greeting:", full_greeting)
# Updating string using slicing
mutable_string = "mutable"
mutable_list = list(mutable_string) # Convert to a list
mutable_list[3] = 'a' # Change the character at index 3
updated_string = ''.join(mutable_list) # Convert back to string
print("Updated:", updated_string)
Explanation:
In this code:
Code:
# Original string
original_string = "Hello, World!"
# Deleting characters using slicing
deleted_string = original_string[:7] + original_string[13:]
print("Original:", original_string)
print("Deleted:", deleted_string)
In this example, the deleted_string is created by excluding the characters at indices 7 to 12 (inclusive) from the original_string. The result is a new string with the characters effectively "deleted."
Code:
# Original string
original_string = "Hello, World!"
# Deleting a substring using replace
deleted_substring = original_string.replace("Hello, ", "")
print("Original:", original_string)
print("Deleted Substring:", deleted_substring)
In this case, the replace() method replaces the "Hello, " substring with an empty string, effectively removing it from the original string.
Code:
# Concatenation
string1 = "Hello, "
string2 = "World!"
concatenated_string = string1 + string2
print("Concatenated:", concatenated_string)
# Repetition
repeated_string = string1 * 3
print("Repeated:", repeated_string)
# Membership
check_membership = "Hello" in concatenated_string
print("Membership Check:", check_membership)
# String Formatting (using f-strings)
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print("Formatted:", formatted_string)
# Length (using len())
length = len(concatenated_string)
print("Length:", length)
Explanation:
In this example:
Code:
# Using %-formatting (old-style formatting)
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print("Formatted (%%-formatting):", formatted_string)
# Using str.format() method (new-style formatting)
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print("Formatted (str.format()):", formatted_string)
# Using f-strings (formatted string literals)
formatted_string = f"My name is {name} and I am {age} years old."
print("Formatted (f-strings):", formatted_string)
# Formatting floating-point numbers
pi = 3.14159
formatted_float = "The value of pi is {:.2f}".format(pi)
print(formatted_float)
# Formatting with named placeholders
formatted_named = "Name: {n}, Age: {a}".format(n=name, a=age)
print(formatted_named)
# Using positional placeholders with str.format()
formatted_pos = "Name: {0}, Age: {1}".format(name, age)
print(formatted_pos)
# Combining positional and named placeholders
combined_formatted = "Name: {}, Age: {a}".format(name, a=age)
print(combined_formatted)
Explanation:
In these example:
Understanding string methods is crucial for any professional looking to upskill in Python. These methods form the foundation of text processing and manipulation, which are common tasks in various fields like data science, web development, and automation. upGrad offers a variety of upskilling courses that can help you master Python and other essential skills required in the modern job market.
1. What are some commonly used string methods in Python?
Some commonly used string methods in Python include upper, lower, replace, split, and join, among others.
2. What is string slicing in Python?
String slicing in Python refers to selecting a range of characters from a string using their index positions.
3. Are there any similarities between string and list methods in Python?
Yes, there are similarities between string and list methods in Python. Both lists and strings have methods for finding elements, counting elements, and checking if elements exist.
4. Are there any special modules in Python for string manipulation?
Yes, Python has a built-in module called string. This provides additional functions and constants for string manipulation that aren't included in the built-in str class.
5. Are there any alternatives to using string methods in Python?
Python provides regular expressions (regex) as a powerful alternative for advanced string manipulation. However, for basic operations, string methods are more efficient.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...