String Operation

String Operation

String Operation

String Operation:

Python provides many built-in string operations that you can use to manipulate strings. Here are some common string operations in Python:

  • Concatenation: You can concatenate two or more strings using the “+” operator.

Example:

				
					str1 = "Hello" 
str2 = "world"
 result = str1 + " " + str2
 print(result) 
				
			

Output:

				
					Hello world
				
			
  • Substring: You can extract a substring from a string using slicing. Slicing uses the colon (:) operator to specify a range of characters to extract.

Example:

				
					str1 = "Hello world"
 substring = str1[6:11] 
print(substring) 
				
			

Output:

				
					world
				
			
  • Replacement: You can replace a portion of a string with another string using the replace() method.

Example:

				
					str1 = "Hello world" 
new_str = str1.replace("world", "Python")
 print(new_str) 
				
			

Output:

				
					Hello Python 
				
			
  • Splitting: You can split a string into a list of substrings using the split() method. You can specify a delimiter character to split the string.

Example:

				
					str1 = "Hello,world" 
split_str = str1.split(",")
 print(split_str) 
				
			

Output:

				
					 ['Hello', 'world'] 
				
			
  • Formatting: You can format a string using the format() method. You can specify placeholders in the string that will be replaced with values.

Example:

				
					name = "John" 
age = 25 
formatted_str = "My name is {} and I am {} years old".format(name, age)
print(formatted_str) 
				
			

Output:

				
					My name is John and I am 25 years old 
				
			
Join To Get Our Newsletter
Spread the love