Modify the value of a string in Python

Source: Internet
Author: User

Demo

info = ' ABC '

If you want to replace the C in the above string info with D, how do I do it?

Method One: Use the Replace () method in Python

Grammar:

  Str. Replace(old, new[, Max])


Parameters:

    • Old--the substring to be replaced.
    • New-A string that replaces the old substring.
    • Max--Optional string, replace no more than Max Times
" ABC ">>> str = info.replace ("C","D")
Print (str)
'abd'

This approach is done by assigning a data object to a new variable to achieve the effect of the substitution.

Method Two: Use the list () method to convert the type of the string into a list type that can be changed, and then use the "". Join () method to combine the results into a string

" ABC ">>> b = list (info)"D"" ". Join (b)print  (info) Abd

It is important to note that in Python, the string data type is immutable, and when the data object is assigned to a variable, the variable is actually a reference to the object, not the value of the object. So the above method changes the string members by assigning them to a new variable. Gets a reference to the changed value by generating a new variable.

  

Modify the value of a string in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.