Open In App

Python - Insert characters at start and end of a string

Last Updated : 06 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python programming, a String is an immutable datatype. But sometimes there may come a situation where we may need to manipulate a string, say add a character to a string.

Let’s start with a simple example to insert characters at the start and end of a String in Python.

Python
s = "For"
s2 = "Geeks"

r = s2 + s + s2
print(r)

Output:

GeeksForGeeks

Explanation: The word "Geeks" is inserted at the start and the end of the string "For". As there is no white space in any of the strings, the words are joined together as one word.

Using String Concatenation

The most common way to join two or more strings is using the String Concateniation method, which used the "+" operator to combine the strings

Python
s = "GeeksForGeeks"

# inserting same characters
r = "Hello" + s + "Hello"
print(r)

# inserting different characters
r = "Hello" + s + "World"
print(r)

Output:

HelloGeeksForGeeksHello
HelloGeeksForGeeksWorld

Using join() Function

The join() function is also used to concatenate two or more strings in Python. It takes an iterable, that is a list or a tuple as the parameters and join them in the given order.

Python
s = "GeeksForGeeks"

# inserting same characters
r = "".join(["Hello", s, "Hello"])
print(r)

# inserting different characters
r = "".join(["Hello", s, "World"])
print(r)

Output:

HelloGeeksForGeeksHello
HelloGeeksForGeeksWorld

Using f-String

The f-string in Python is used in string formatting. It directly embeds the expression inside the curly braces.

Python
s = "GeeksForGeeks"

# inserting same characters
r = f"Hello{s}Hello"
print(r)

# inserting different characters
r = f"Hello{s}World"
print(r)

Output:

HelloGeeksForGeeksHello
HelloGeeksForGeeksWorld

Using format() Function

The Python format() function is an inbuilt function used to format strings. Unline f-string, it explicitly takes the expression as arguments.

Python
s = "GeeksForGeeks"

# inserting same characters
r = "Hello{}Hello".format(s)
print(r)

# inserting different characters
r = "Hello{}World".format(s)
print(r)

Output:

HelloGeeksForGeeksHello
HelloGeeksForGeeksWorld

Next Article

Similar Reads