Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting characters at the start and end of a string

Tags:

python

People also ask

How do you add a character at the beginning and at the end of a string?

Method 1: By using +: We can add a character to the end or start of a string by using +.

How do you insert a character at the beginning of a string?

1. Using String. Insert a character at the beginning of the String using the + operator. Insert a character at the end of the String using the + operator.

How do you add a character to the beginning and end of a string in Python?

Add a Character to a String in Python Using the + Operator The + operator can concatenate two strings or a string and a character and returns a new string in Python.


Strings are immutable so you can't insert characters into an existing string. You have to create a new string. You can use string concatenation to do what you want:

yourstring = "L" + yourstring + "LL"

Note that you can also create a string with n Ls by using multiplication:

m = 1
n = 2
yourstring = ("L" * m) + yourstring + ("L" * n)

For completeness along with the other answers:

yourstring = "L%sLL" % yourstring

Or, more forward compatible with Python 3.x:

yourstring = "L{0}LL".format(yourstring)

You can also use join:

yourstring = ''.join(('L','yourstring','LL'))

Result:

>>> yourstring
'LyourstringLL'

If you want to insert other string somewhere else in existing string, you may use selection method below.

Calling character on second position:

>>> s = "0123456789"
>>> s[2]
'2'

Calling range with start and end position:

>>> s[4:6]
'45'

Calling part of a string before that position:

>>> s[:6]
'012345'

Calling part of a string after that position:

>>> s[4:]
'456789'

Inserting your string in 5th position.

>>> s = s[:5] + "L" + s[5:]
>>> s
'01234L56789'

Also s is equivalent to s[:].

With your question you can use all your string, i.e.

>>> s = "L" + s + "LL"

or if "L" is a some other string (for example I call it as l), then you may use that code:

>>> s = l + s + (l * 2)