inserting characters at the start and end of a string

前端 未结 7 1197
灰色年华
灰色年华 2020-12-02 14:06

I am new and trying to find a way to insert a number of L\'s at the beginning and end of a string. So if I have a string which says

\"where did I put my cupcake thi

相关标签:
7条回答
  • 2020-12-02 14:25

    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)
    
    0 讨论(0)
  • 2020-12-02 14:26

    Let's say we have a string called yourstring:

    for x in range(0, [howmanytimes you want it at the beginning]):
        yourstring = "L" + yourstring
    for x in range(0, [howmanytimes you want it at the end]):
        yourstring += "L"
    
    0 讨论(0)
  • 2020-12-02 14:31

    I am rendering a URL by user input. There if user enter a string with two words I want to print the word with + in between

    Example

    key = input("Enter the product :")
    
    URL = "http://exmaple.com/"
    
    print (URL)
    
    User input: iphone 11
    

    For the above code, I get a URL as "http://exmaple.com/iphone 11"

    But I want to print the URL as "http://exmaple.com/iphone+11"

    0 讨论(0)
  • 2020-12-02 14:43

    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)
    
    0 讨论(0)
  • 2020-12-02 14:43

    You can also use join:

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

    Result:

    >>> yourstring
    'LyourstringLL'
    
    0 讨论(0)
  • 2020-12-02 14:44

    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)
    
    0 讨论(0)
提交回复
热议问题