Saturday, April 7, 2012

Python: How to insert characters to the string at the end

Reference: http://stackoverflow.com/q/10059554/1276534
Credits: user1319219, Akavall, Mark Byers

Just in case you wondering what are the ways to insert character to the string at the front or back (beginning or end) of a string. Here are the ways to do it. Notice, string is immutable object, so you can not insert anymore characters into it. All we are doing is create a new string, and assign it to the variable. (That's why I did not use the same name, because I want to emphasize they are NOT the same string). But you can just as well use text = (any method)

# Create a new string that have 1 x in the beginning, and 2 x at the end
# So I want the string to look like this 'xHello Pythonxx'
text = 'Hello Python'

# Method 1, string concatenation
new_text = 'x' + text + 'xx'

# Method 2, create a new string with math operators
i = 1
j = 2
new_text = ('x'*i) + text + ('x'*j)

# Method 3, use the string's join() method
# You are actually joining the 3 part into a originally empty string
new_text = ''.join(('x', text, 'xx'))
And in case you don't trust me and want to see the output:
xHello Pythonxx
xHello Pythonxx
xHello Pythonxx

1 comment:

  1. #I am learning python and still wonder how works the part of code:
    ' '.join()
    #how does ' ' work? How should I identify the need for it in my code

    ReplyDelete