In Python, a string is a sequence of characters that can be manipulated using various functions and methods.
Some of the main ways to manipulate strings are
Slicing: Extracting a substring from a larger string by specifying a range of indices. Basic syntax is :
str[start:end:step]
string = "Hello" string[1:4] # "ell" #starting from position 1 to string[:4] # "Hell" string[2:] # "llo" string[:] # "Hello" '''You can use negative indices to slice from the end, and specify a step to slice with a stride''' string = "Hello" string[-4:-1] # "ell" string[::-1] # "olleH" string[::2] # "Hlo"
String methods: Useful functions to manipulate strings(
lower()
,upper()
,split()
,join()
,replace()
,find()
)string = 'Learn Python' string.lower() # returns 'learn python' string.upper() # returns 'LEARN PYTHON' #string to list string = 'Learn Python Programming' print(string.split(' ')) # output = ['Learn', 'Python', 'Programming'] #list to string parts = ['Learn', 'Python', 'Programming'] string.join(parts) # output = 'Learn Python Programming' string = 'Learn Python Programming' string.replace('Python', 'Java') # output = 'Learn Java Programming' string = 'Bitsnotion'.find('s') print(abc)# output = 3
String formatting: Integrate variables into strings.
Python offers various methods for string formatting:
The
f-strings
(available in Python 3.6+)The
str.format()
methodThe
%
operator (deprecated in Python 3)
name = "Nirmal"
age = 23
print(f"Hello, my name is {name} and I'm {age} years old.")
print("Hello, my name is {} and I'm {} years old.".format(name, age))
# BOth output = "Hello, my name is Nirmal and I'm 23 years old."
String concatenation: Combine multiple strings using the + operator or .join() method.
string1 = "Hello" string2 = "World!" #method -1 print(string1 + string2) ## output = Hello World! #method-2 string1 += string2 print(string1) # output = Hello World! #method-3 print("".join([string1, string2])) # HelloWorld!