Basic Python-string, basic python string

Source: Internet
Author: User

Basic Python-string, basic python string
String Creation

s = "Hello World"
String Common Operations

Join ()Concatenates the elements in the sequence with specified characters to generate a new string.

>>> s = ["1", "2", "3", "4"]>>> ".".join(s)1.2.3.4

Strip ()Removes the specified character (space by default) from the start or end of a string)

>>> s = " Hello World ">>> s.strip()Hello World
>>> s = "*Hello World&"
>>> s.strip("*")
Hello World&

Lstrip ()Truncates spaces or specified characters on the left of the string.

>>> s = "*Hello World*">>> s.lstrip("*")Hello World*

Index(Str,Beg=0, End=Len(String))Check whether the string contains the substring 'str'. If it does not exist, an error is returned (beg: Start position, default value: 0; end: end position, default value: the last position of the string)

>>> s = "Hello World">>> s.index("e")1>>> s.index("z")ValueError:substring not found

Rindex ()Returns the position of the last occurrence of a string. If not, an error is returned.

>>> s = "Hello World">>> s.rindex("o")7

Find ()Checks whether the string contains a substring str. If no substring exists,-1 is returned.

>>> s = "Hello World">>> s.find("e")1>>> s.find("z")-1

Rfind ()Returns the position of the last occurrence of a string. If no match exists,-1 is returned.

Split(Str="",Num=String.Count(Str))Slice the string by specifying a separator (str: Specifies the string, default is all null characters; num: number of times of separation), return to the list

>>> s = "www.luffycity.com">>> s.split(".")['www', 'luffycity', 'com']

Splitlines ()Returns a list containing rows as elements, separated by rows ('\ R',' \ r \ n', \ n ').

>>> s = """luffycitynamei""">>> s.splitlines()['luffycity', 'namei']

Count(Sub,Start= 0,End=Len(String))Count the number of times a character appears in a string (sub: Statistical string)

>>> s = "Hello World">>> s.count("o", 2, 9)2

Replace(Old, New[,Max])Replace the substring in the string (old: old string; new: new string; max: Maximum number of times of replacement)

>>> s = "Hellz Wzrld">>> s.replace("z", "o")Hello World

Endswith ()End with a specified suffix?

>>> s = "Hello World">>> s.endswith("d")True>>> s.endswith("l")False

Startswith ()Whether to start with a specified string

>>> s = "Hello World">>> s.startswith("H")True>>> s.startswith("e")False

Isdigit ()Digit or not

>>> s = "12345">>> s.isdigit()True>>> s = "asdfg">>> s.isdigit()False

Isalnum ()Whether it is composed of letters and numbers

Isalpha ()Whether it is composed of letters only

Isdecimal ()Whether it only contains decimal characters

Isidentifier ()Whether it contains reserved words for the language

Islower ()Whether it is composed of lower-case letters

Isprintable ()Printable or not

Isspace ()Whether it is composed of only white spaces

Istitle ()Whether the first letter of a word is in upper case and the other letters are in lower case

Title ()Returns a title string. All words start with uppercase and all other letters are lowercase.

>>> s = "hello world">>> s.title()Hello World

Isupper ()Are all uppercase letters?

Upper ()Converts lowercase letters to uppercase letters.

>>> s = "Hello World">>> s.upper()HELLO WORLD

Capitalize ()Uppercase letters and lowercase letters

1 >>> s='hello world'2 >>> s.capitalize()3  'Hello world'

Casefold ()Convert uppercase letters to lowercase letters

>>> s='Hello World'>>> s.casefold() 'hello world'

Lower ()All uppercase characters in the string are lowercase and only apply to 'a ~ Z'

Swapcase ()Convert uppercase and lowercase letters

>>> s = "Hello World">>> s.swapcase()hELLO wORLD

Center (width [, fillchar])If width is less than the string width, a string is directly returned. Otherwise, fillchar is used for filling (width: specified width; fillchar: filled character)

>>> s = "Hello World">>> s.center(25, "*")*******Hello World*******       

Ljust(Width[,Fillchar])Returns a new string with the left alignment of the original string and spaces filled in to the specified length. If the specified length is less than the length of the original string, the original string is returned (width: specified width; fillchar: filled character)

>>> s = "Hello World">>> s.ljust(25, "*")Hello World**************

Must UST(Width[,Fillchar])Returns a new string with the right alignment of the original string and filled with spaces to the width. If the specified length is less than the length of the string, the original string is returned.

>>> s = "Hello World">>> s.ljust(25, "*")**************Hello World

Edcode ()Encode a string in the specified encoding format

>>> s = "Hello World">>> s.encode(encoding="utf-8")b'Hello World

Expandtabs ()Convert the tab character ('\ t') in the string to a space. The default value is 8.

>>> s = "\t Hello World \t">>> s.expandtabs(16)                 Hello World    

Partition ()Returns a triple of 3 RMB. The first is the substring on the left of the separator, the second is the separator itself, and the third is the substring on the right of the separator.

>>> s = "Hello.World">>> s.partition(".")('Hello', '.', 'World')

Zfill ()Returns the string of the specified length. The original string is right-aligned and filled with 0 in front.

>>> s = "Hello World">>> s.zfill(25)00000000000000Hello World

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.