Home >Backend Development >Python Tutorial >Several commonly used string functions in python

Several commonly used string functions in python

尚
forward
2020-06-15 17:03:443806browse

Several commonly used string functions in python

1. lower() changes all characters to lowercase

2. upper() changes all characters to uppercase

3. swapcase( ) Case swap

4. title() capitalizes the first letter of each word. It uses all the characters of English letters to distinguish whether it is a word,

eg:s = "a是傻b"
s2 = s.title()
结果为"A傻B",a和b都变成了大写,因为他是根据英文字母来区别是否为一个单词的,此处a和b都被系统默认为了一个单词.

5. center (Numbers, characters) Stretch the string by a unit, put the original string in the middle, and fill in the remaining positions with "*".

6. Strip() removes the blanks on the left and right sides of the string by default, but please note Only remove the left and right sides without including the white space in the middle. And strip() can specify to remove the content at the left and right ends.

eg:s1 = "aba"
s2 = s1.strip(a)
结果为:"b"

7. replace(): Replace the specified content in the string

eg:s1 = "我很帅"
s2 = s1.replace("帅","不帅")
结果为:"我很不帅",把"帅"替换成了"不帅"

And replace() can specify the number of times to replace the content, but it requires that the number of content items to be replaced in the string is greater than or equal to the number of times to be replaced. For example: s1 = "we are", there are two e , then you can stipulate that you want to replace the content less than twice.

eg:s2 = s1.replace("e","a",2)
结果为:s2 = "wa ara"

When the characters you want to replace exist in the string more than once, the system will based on the order of these contents in the string, To judge the first few to change.

For more related knowledge, please pay attention to thepython video tutorialcolumn

The above is the detailed content of Several commonly used string functions in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete