2 ways to replace Python strings

Source: Internet
Author: User
Python string substitution is a frequently encountered problem when Python is manipulating strings, so here's a quick introduction to the string substitution method.

Python string substitution can be implemented in 2 ways:
1 is the method of using the string itself.
2 replacing a string with a regular

Here's an example to experiment with:
A = ' Hello word '
Replace word in a string with Python

1. Replace method with string itself

Copy the Code code as follows:


A.replace (' word ', ' python ')

The result of the output is Hello Python

2, use regular expressions to complete the replacement:

Copy the Code code as follows:


Import re
Strinfo = Re.compile (' word ')
b = strinfo.sub (' python ', a)
Print B

The result of the output is also Hello Python

As for which method to use, look at your own choice.

  • 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.