String of pythons data type

String(string)
1 Overview

​ A string is any text enclosed in single or double quotes, such as "abc", 'xy', etc. Please note that '' or "" itself is only a representation, not part of the string.

a. What if the string contains single quotes and double quotes?

print('I\'m \"ok\"')

The represented string content is:

I'm "ok"

Note: The escape character \ can escape many characters, such as \n for newline, \t for tab, and the character \ itself also needs to be escaped, so the character represented by \\ is \, etc.

>>>print('I\'m ok.')
I'm ok.
>>>print('I\'m learning\n python.')
I'm leanring
Python.
>>> print('\\\n\\')
\
\

However, if there are many strings in the string that need to be escaped, a lot of them need to be added. To simplify, python also allows r"" (or R"") to indicate that the internal strings are not escaped by default.

>>> print('\\\t\\')
\   \
>>>print(r'\\\t\\')
\\\t\\

If there are many newlines in the string, it is not easy to read in one line with \n. To simplify, python allows the format of "'..."' to represent multiple lines:

>>> print('''line1
    line2
    line3''')
line1
line2
line3
2. Create a string
str1 = "hello world"
str2 = 'you are good'
3. String operations
3.1 String concatenation

3.1.1 Using the plus sign to connect

#字符串的连接,通过“+”进行连接
s1 = 'welcome '
s2 = 'to guangzhou'
print(s1 + s2)
输出:
welcome to guangzhou

Note: String + number, this will report an error, and different types cannot be added

3.1.2 Use "," to connect [tuple type]

s1 = 'hello'
s2 = 'world'
print(s1, s2)
#使用“,”连接的时候,在“,”的位置会产生一个空格
输出:
hello world

3.1.3 Formatting connections using %

s1 = 'hello'
s2 = 'world'
print("%s %s"%(s1, s2))
输出:
hello world

3.1.4 Using the join function to join

s1 = ['hello', 'world']
print("".join(s1))
print("*".join(s1))
输出:
helloworld
hello*world

Note: "".join() function only needs to pass one parameter [string, list, tuple, dictionary (unordered output), set (unordered output), the elements of which should be of string type].

3.2 Repeated output string
#重复输出字符串,通过乘法的方式实现
s3 = 'good'
print(s3 * 3)
输出:
goodgoodgood
3.3 Get characters in a string
#通过索引的方式实现
#索引:给一个字符串中的字符从0开始编号,也称为下标
#索引的取值范围:[0,len(str)-1]
#访问方式: 变量名称[索引]
str3 = 'good'
print(str3[0])
#索引值还可以从-1开始,-1代表倒数第一个字符
print(str3[-1])
输出:
g
d
3.3 Intercept string
# 通过下标截取字符串
str1 = "hello world"
print(str1[3:6])
#注意:截取字符串的范围是str[start : end] 它是一个前闭后开的区间[start,end)
#如果n的值超过了字符串的最大长度,则仍然截取原下标的长度

#从开头截取到指定索引之前[0,5)
print(str1[:5])

#从指定截取到结尾[4,len(str1))
print(str1[4:])

#注意在使用str[start : end]来截取字符串的时候,若start不写默认从第一个字符开始
#若end不写,则默认到最后一个字符结束。取头去尾。
print("012345"[1:-1])
输出:
lo 
hello
o world
1234
3.5 Determine whether it contains the specified character
#判断字符串中是否包含某指定字符串
str4 = "you are a good boy"
print("good" in str4)
#若包含有则返回True否则为False
输出:
True
3.6 Formatting output
#通过%来改变后面的字母或者是符号的含义,%被称为占位符
# %s:格式化字符串
# %d:格式化整数
# %f:格式化浮点数,可指定小数点后的精度
age = 18
name = "丽丽"
weight = 45.5
print("my name is %s , I am %d year old and my weight is %.2f kg"%(name, age, weight))
#注意:%.nf表示精确到小数点后n位,会四舍五入
输出:
my name is 丽丽 , I am 18 year old and my weight is 45.50 kg
4. About String Common Functions
4.1 eval(str)

Function: Evaluate the string str as a valid expression and return the result.

Can convert list, tuple, dict and string to each other

>>>num1 = eval('123')
>>>print(num1)
123

>>>num2 = eval("[1, 2, 3]")
>>>print(num2)
[1, 2, 3]

>>> num3 = eval("12-3")
>>> print(num3)
9
4.2 len (page)

Function: Return the length of the current string (number of characters)

>>> len("you are good")
12
4.3 str.lower()

Function: Returns a string that converts uppercase letters in a string to lowercase letters

>>> str = "Hello World"
>>> print(str.lower())
hello world

Note: This method does not change the original characters

4.4 str.upper()

Function: Returns a string that converts lowercase letters in the string to uppercase letters

>>> str = "Hello World"
>>> print(str.upper())
HELLO WORLD
4.5 str.swapcase ()

Function: Returns a string that converts uppercase letters in a string to lowercase letters and lowercase letters to uppercase letters

>>> str = "Hello World"
>>> print(str.swapcase())
hELLO wORLD
4.6 str.capitalize()

Returns a string with the first letter uppercase and others lowercase

>>> str = "Hello World"
>>> print(str.capitalize())
Hello world
4.7 str.title()

Returns a string with the first letter of each word capitalized

>>> str = "Hello World"
>>> print(str.title())
Hello World
4.8 str.center(width[, fillchar])

Function: Returns a centered string with a specified width, fillchar is the filled string, and spaces are used by default

>>> str = "Hello World"
>>> print(str.center(50,"*"))
*******************Hello World********************
4.9 str.ljust (width [, fillchar])

Function: Returns a left-aligned string with the specified width, fillchar is the fill character. padding with spaces by default

>>> str = "Hello World"
>>> print(str.ljust(50,"*"))
Hello World***************************************
4.10 str.rjust(width[, fillchar])

Function: Returns a right-aligned string with a specified width, fillchar is the fill character, and the default is to fill with spaces

>>> str = "Hello World"
>>> print(str.rjust(50,"*"))
***************************************Hello World
4.11 str.zfill(width)

Function: Returns a string with a length of width, the original string is right-aligned, and the front is filled with 0

>>> str = "Hello World"
>>> print(str.zfill(50))
000000000000000000000000000000000000000Hello World
4.12 str.count(str 【,start】【, end】)

Function: Returns the number of occurrences of str in the string. You can specify a range. If not specified, the default is from the beginning to the end, and the matching is case-sensitive.

>>> str = "Hello World"
>>> print(str.count("hello", 0 , 10))
0
4.13 str.find(str1【, start】【, end】)

Function: Check whether the str1 string is included in the string from left to right, you can specify the range, the default is from the beginning to the end.

Returns the first subscript of the first occurrence, if not found, returns -1

>>> str = "Hello World"
>>> str1 = "llo"
>>> print(str.find(str1, 0 , 10))
2
4.14 str.rfind(str1【, start】【, end】)

Function: similar to str.find(), but searches from the right

>>> str = "Hello World"
>>> str1 = "llo"
>>> print(str.rfind(str1, 0 , 10))
2
4.15 str.index(str1[, start = 0] ,[ end = len(str)])

Function: Similar to find(), different from find(), an exception will be reported if str1 does not exist

>>> str2 = "Hello World"
>>> str1 = "hello"
>>> print(str2.index(str1, 0 , 10))
ValueError: substring not found
4.16 str.lstrip()

Function: Truncate the specified string on the left side of the string, the default is a space

>>> str = '**** you are very good'
>>> print(str.lstrip())
>>> print(str.lstrip())
**** you are very good
>>> print(str.lstrip("*"))
 you are very good
4.17 str.rstrip ()

Function: Truncate the specified string on the right side of the string, the default is a space

>>> str = '**** you are good****'
>>> print(str.rstrip())
**** you are good****
>>> print(str.rstrip("*"))
**** you are good

str1 = "*nih*a*o*"
print(str1.strip('*'))
输出:
nih*a*o
4.18 string.split(str=”“, num=string.count(str))

Function: slice string with str as delimiter, if num has a specified value, only num substrings are separated

str – Delimiter, defaults to all null characters, including spaces, newlines (\n), tabs (\t), etc. num - number of splits

>>> str1 = "hello you are good"
>>> str1.split()
['hello', 'you', 'are', 'good']
>>> str1.split(" ",2)
['hello', 'you', 'are good ']
4.19 str1.splitlines([keepends])

Function: The string will be divided according to the line ('\r','\r\n','\n'), and a list containing each line as an element is returned. If the value of the parameter keepends is False, the newline character is not included. If True, newlines are preserved. The parameter keepends defaults to False.

str2 = '''how are
you ?
i am
fine
!
'''

list2 = str2.splitlines()
print(list2)
输出:
['how are', 'you ?', 'i am', 'fine', '!']
str2 = '''how are
you ?
i am
fine
!
'''

list2 = str2.splitlines(keepends=True)
print(list2)
输出:
['how are\n', 'you ?\n', 'i am\n', 'fine\n', '!\n']
4.20 str1.join(seq)

Function: Combine all elements in seq into a new string with the specified string as the separator.

list2 = ['you', 'are', 'very', 'great', '!']
str3 = ' '.join(list2)
print(str3)
输出:
you are very great !
str1 = "how are you , i am fine thank you"
str3 = "*".join(str1)
print(str3)
输出:
h*o*w* *a*r*e* *y*o*u* *,* *i* *a*m* *f*i*n*e* *t*h*a*n*k* *y*o*u

Note: If the concatenation is a string, it will concatenate each character in the string with the specified character.

4.21 Get the maximum and minimum characters

max (str): Function: Returns the largest letter in the string str

str1 = "how are you , i am fine thank you"
print(max(str1))
输出:
y

min (str): function: returns the smallest letter in the string str

str1 = "how are you , i am fine thank you"
print(min(str1))
输出:
' '

Note: The comparison is ASCII code value

4.22 String replacement

str.replace(old , new [, count])

Function: Replace old in the string with new. If count is not specified, all are replaced by default. If count is specified, the first count will be replaced.

str1 = "how are you , i am fine thank you"
str2 = str1.replace("you" ,'me')
print(str2)
输出:
how are me , i am fine thank me
4.23 Mapping replacement of strings

dic = str.maketrans(oldstr, newstr)

str2.translate(dic)

Parameter 1: The character to be converted Parameter 2: The target character

str5 = ""
dic = str5.maketrans("ac", "21")
# a--2   c--1
str7 = "how  are you  ,u ewe c "
print(str7.translate(dic))
输出:
how  2re you  ,u ewe 1 

Note: Rarely used.

4.24 Determine the beginning and end of a string

str.startswith(str1, start=0, end=len(str))

Function: Determine whether the string starts with the given string within the given range. If no range is specified, the entire string is defaulted.

str1 = "aaa bbb  ccc  deee"
print(str1.startswith("aa"))
str1 = "aaa bbb  ccc  deee"
print(str1.startswith("aa", 3, 9))
输出:
True
False

str.endswith(str, start=0, end=len(str))

Function: Determine whether the string ends with the specified string within the given range. If there is no specified range, the default is the entire string.

str1 = "aaa bbb  ccc  deee"
print(str1.endswith("deee"))
str1 = "aaa bbb  ccc  deee"
print(str1.endswith("e", 3 ,9))
输出:
True
False
4.25 Encoding and Decoding

str.encode(encoding=”utf-8”, errors=”scrict”)

Function: The encoding of the string. If encoding is not specified, utf-8 is selected by default.

str1 = "你好吗?"
data = str1.encode()
print(data)
print(type(data))
输出:
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
<class 'bytes'>

str.decode(encoding=”utf-8”)

“hello”.encode(“utf-8”).decode()

Function: Decode characters, if the encoding format is not specified, utf-8 is selected by default

str1 = "你好吗?"
data = str1.encode()
print(data)
print(type(data))

data2 = data.decode()
print(data2)
print(type(data2))
输出:
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
<class 'bytes'>
你好吗?
<class 'str'>

Note: The encoding format when decoding should be consistent with the encoding format

Extension: when errors = ignore, ignore errors

4.26 Determine whether it is a letter or a number

str.isalpha()

Function: Judging that the string has at least one character, and all characters are letters (or contain Chinese characters), if true, return True, otherwise return False

str8 = "hello ni hao "
print(str8.isalpha())

str9 = "你好"
print(str9.isalpha())
输出:
False
True

str.isalnum()

Function: If a string has at least one character, and all characters are letters or numbers (or contain Chinese characters), then return True, otherwise return False

str9 = '1234你好'
str10 = "sc22xdcd"
str11 = "ss1 2dd"
print(str9.isalnum())
print(str10.isalpha())
print(str11.isalnum())
输出:
True
True
False
4.27 Judging case

str.isupper ()

Function: If the string contains at least one letter character, and these letters are all uppercase, return True, otherwise return False

str10 = "AA2221  你111"
print(str10.isupper())


str10 = "AAaaa"
print(str10.isupper())
输出:
True
False

str.islower()

Function: If the character string contains at least one letter, and all the letters are lowercase, return True, otherwise return False.

str10 = "aa2221  你111"
print(str10.islower())
输出:
True
4.28 Determine whether it contains special characters

1 、 str.istitle ()

Function: Returns True if a string is titled, False otherwise

【Titleization】Each first letter is capitalized.

str1 = "Hello World"
print(str1.istitle())
输出:
True

2、str.isdigit()

Function: Determine whether the characters are all numbers.

isdigit()
True: Unicode numbers, byte numbers (single-byte), full-width numbers (double-byte)
False: Chinese numerals, , Roman numerals
Error: None

print("123".isdigit())
print("123a".isdigit())
输出:
True
Fals

3、str.isnumeric()

Function: If the string contains only numeric characters, return True, otherwise return False.

isnumeric()
True: Unicode numbers, full-width numbers (double-byte), Chinese numbers
False: Roman numerals,
Error: byte numbers (single-byte)

print("123一".isnumeric())
print("123a".isnumeric())
输出:
True
False

4 、 decimal page ()

Function: Check if the string contains only decimal characters [0, 9], if so, return True, otherwise return False.

isdecimal()
True: Unicode numbers, full-width numbers (double-byte),
False: Roman numbers, Chinese numbers
Error: byte numbers (single-byte)

print("123".isdecimal())
print("123z".isdecimal())
输出:
True
False

5 、 str.isspace ()

Function: Returns True if the string contains only spaces, otherwise returns False.

print(" ".isspace())
print("\t".isspace())
print("\n".isspace())
print("\r".isspace())
print("  qq".isspace())
输出:
True
True
True
True
False
4.29 ASCII code conversion

1 word (size)

Function: Get the integer representing the ASCII code value of the string.

print(ord("A"))
print(ord("你"))
输出:
65
20320

2、chr(str)

Function: Convert the encoding to the corresponding character.

print(chr(68))
print(chr(20190))
输出:
D

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324696038&siteId=291194637