>  기사  >  백엔드 개발  >  파이썬 문자열 요약, 모아두는 걸 추천!

파이썬 문자열 요약, 모아두는 걸 추천!

WBOY
WBOY앞으로
2023-04-12 19:10:111059검색

파이썬 문자열 요약, 모아두는 걸 추천!

Python 문자열이란 무엇입니까?

문자열은 일련의 문자를 포함하는 객체입니다. 문자는 길이가 1인 문자열입니다. Python에서는 개별 문자도 문자열입니다. 그런데 더 흥미로운 점은 Python 프로그래밍 언어에는 문자 데이터 유형이 없지만 C, Kotlin, Java 등 다른 프로그래밍 언어에는 문자 데이터 유형이 있다는 것입니다

작은따옴표, 큰따옴표, 삼중따옴표를 사용할 수 있습니다. 또는 str() 함수를 사용하여 Python 문자열을 선언합니다. 다음 코드 조각은 Python에서 문자열을 선언하는 방법을 보여줍니다.

# A single quote string
single_quote = 'a'# This is an example of a character in other programming languages. It is a string in Python
# Another single quote string
another_single_quote = 'Programming teaches you patience.'
# A double quote string
double_quote = "aa"
# Another double-quote string
another_double_quote = "It is impossible until it is done!"
# A triple quote string
triple_quote = '''aaa'''
# Also a triple quote string
another_triple_quote = """Welcome to the Python programming language. Ready, 1, 2, 3, Go!"""
# Using the str() function
string_function = str(123.45)# str() converts float data type to string data type
# Another str() function
another_string_function = str(True)# str() converts a boolean data type to string data type
# An empty string
empty_string = ''
# Also an empty string
second_empty_string = ""
# We are not done yet
third_empty_string = """"""# This is also an empty string: ''''''

Python에서 문자열을 가져오는 또 다른 방법은 input() 함수를 사용하는 것입니다. input() 함수를 사용하면 입력된 값을 키보드를 사용하여 프로그램에 삽입할 수 있습니다. 삽입된 값은 문자열로 읽혀지지만 다른 데이터 유형으로 변환할 수 있습니다.

# Inputs into a Python program
input_float = input()# Type in: 3.142
input_boolean = input() # Type in: True
# Convert inputs into other data types
convert_float = float(input_float)# converts the string data type to a float
convert_boolean = bool(input_boolean) # converts the string data type to a bool

Python에서 객체의 데이터 유형을 결정하기 위해 type() 함수를 사용합니다. 이 함수는 객체의 클래스를 반환합니다. 객체가 문자열이면 str 클래스를 반환합니다. 마찬가지로 객체가 사전, 정수, 부동 소수점, 튜플 또는 부울인 경우 각각 dict, int, float, tuple, bool 클래스를 반환합니다. 이제 type() 함수를 사용하여 이전 코드 조각에서 선언된 변수의 데이터 유형을 결정해 보겠습니다.

# Data types/ classes with type()
print(type(single_quote))
print(type(another_triple_quote))
print(type(empty_string))
print(type(input_float))
print(type(input_boolean))
print(type(convert_float))
print(type(convert_boolean))

Python 문자열 문자가 포함된 ASCII 테이블

ASCII(American Standard Code for Information Interchange)는 매핑을 돕기 위해 설계되었습니다. 숫자 집합이 텍스트보다 컴퓨터 메모리에 저장하기 쉽기 때문에 문자 또는 텍스트를 숫자로 변환합니다. ASCII는 주로 영어로 128자를 인코딩하며 컴퓨터 및 프로그래밍에서 정보 처리에 사용됩니다. ASCII로 인코딩된 영어 문자에는 소문자(a-z), 대문자(A-Z), 숫자(0-9), 문장 부호 및 기타 기호가 포함됩니다.

ord() 함수는 길이가 1(1자)인 Python 문자열을 다음으로 변환합니다. ASCII 테이블의 십진수 표현과 chr() 함수는 십진수 표현을 다시 문자열로 변환합니다. 예:

import string
# Convert uppercase characters to their ASCII decimal numbers
ascii_upper_case = string.ascii_uppercase# Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ
for one_letter in ascii_upper_case[:5]:# Loop through ABCDE
print(ord(one_letter))

Output:

65
66
67
68
69
# Convert digit characters to their ASCII decimal numbers
ascii_digits = string.digits# Output: 0123456789
for one_digit in ascii_digits[:5]:# Loop through 01234
print(ord(one_digit))

Output:

48
49
50
51
52

위의 코드 조각에서는 ABCDE 및 01234 문자열을 반복하고 각 문자를 ASCII 테이블의 10진수 표현으로 변환합니다. chr() 함수를 사용하여 반대 작업을 수행하여 ASCII 테이블의 십진수를 Python 문자열 문자로 변환할 수도 있습니다. 예:

decimal_rep_ascii = [37, 44, 63, 82, 100]
for one_decimal in decimal_rep_ascii:
print(chr(one_decimal))

Output:

%
,
?
R
d

ASCII 테이블에서 위 프로그램의 출력에 있는 문자열 문자는 해당 십진수에 매핑됩니다.

문자열 속성

Zero 인덱스: 첫 번째 요소의 인덱스 string은 0이고 마지막 요소의 인덱스는 len(string) - 1입니다. 예:

immutable_string = "Accountability"
print(len(immutable_string))
print(immutable_string.index('A'))
print(immutable_string.index('y'))

Output:

14
0
13

불변성: 이는 문자열의 문자를 업데이트할 수 없음을 의미합니다. 예를 들어 문자열에서 요소를 제거하거나 해당 인덱스 위치에 새 요소를 할당하려고 시도할 수 없습니다. 문자열을 업데이트하려고 하면 TypeError:

immutable_string = "Accountability"
# Assign a new element at index 0
immutable_string[0] = 'B'

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_11336/2351953155.py in
2
3 # Assign a new element at index 0
----> 4 immutable_string[0] = 'B'
TypeError: 'str' object does not support item assignment

가 발생합니다. 하지만 문자열을 immutable_string 변수에 다시 할당할 수는 있지만 메모리를 가리키지 않기 때문에 동일한 문자열이 아니라는 점에 유의해야 합니다. 같은 개체. Python은 이전 문자열 개체를 업데이트하지 않습니다. ID로 볼 수 있듯이 새 문자열 개체를 만듭니다.

immutable_string = "Accountability"
print(id(immutable_string))
immutable_string = "Bccountability"
print(id(immutable_string)
test_immutable = immutable_string
print(id(test_immutable))

Output:

2693751670576
2693751671024
2693751671024

위의 두 ID는 동일한 컴퓨터에서도 다릅니다. 즉, 두 immutable_string 변수는 모두 다음을 가리킵니다. 메모리의 주소가 다릅니다. 마지막 immutable_string 변수를 test_immutable 변수에 할당합니다. test_immutable 변수와 마지막 immutable_string 변수가 동일한 주소를 가리키는 것을 볼 수 있습니다.

연결: 두 개 이상의 문자열을 함께 연결하여 + 기호를 사용하여 새 문자열을 얻습니다. 예:

first_string = "Zhou"
second_string = "luobo"
third_string = "Learn Python"
fourth_string = first_string + second_string
print(fourth_string)
fifth_string = fourth_string + " " + third_string
print(fifth_string)

Output:

Zhouluobo
Zhouluobo Learn Python

Repeat: * 기호를 사용하여 문자열을 반복할 수 있습니다. 예:

print("Ha" * 3)

Output:

HaHaHa

인덱싱 및 슬라이싱: 문자열이 0부터 인덱싱되고 해당 인덱스 값을 사용하여 문자열의 모든 요소에 액세스할 수 있음을 확인했습니다. 두 개의 인덱스 값을 분할하여 문자열의 하위 집합을 얻을 수도 있습니다. 예:

main_string = "I learned English and Python with ZHouluobo. You can do it too!"
# Index 0
print(main_string[0])
# Index 1
print(main_string[1])
# Check if Index 1 is whitespace
print(main_string[1].isspace())
# Slicing 1
print(main_string[0:11])
# Slicing 2:
print(main_string[-18:])
# Slicing and concatenation
print(main_string[0:11] + ". " + main_string[-18:])

Output:

I
True
I learned English
You can do it too!
I learned English. You can do it too!

String method

str.split(sep=None, maxsplit=-1): 문자열 분할 방법에는 sep 및 maxsplit의 두 가지 속성이 포함됩니다. 이 메서드를 기본값으로 호출하면 공백이 있는 곳마다 문자열이 분할됩니다. 이 메소드는 문자열 목록을 반환합니다:

string = "Apple, Banana, Orange, Blueberry"
print(string.split())

Output:

['Apple,', 'Banana,', 'Orange,', 'Blueberry']

분할된 문자열에 ,가 포함되어 있으므로 문자열이 잘 분할되지 않은 것을 볼 수 있습니다. sep=',' 를 사용하여 , :

print(string.split(sep=','))

출력:

['Apple', ' Banana', ' Orange', ' Blueberry']

이 있는 곳을 분할할 수 있습니다. 이는 이전 분할보다 낫지만 일부 분할 문자열 앞에 공백이 있는 것을 볼 수 있습니다. (sep=', ')를 사용하여 제거할 수 있습니다.

# Notice the whitespace after the comma
print(string.split(sep=', '))

출력:

['Apple', 'Banana', 'Orange', 'Blueberry']

이제 문자열이 멋지게 분할되었습니다. 때로는 최대 횟수를 분할하고 싶지 않은 경우 maxsplit 속성을 사용하여 분할하려는 횟수를 지정할 수 있습니다.

print(string.split(sep=', ', maxsplit=1))
print(string.split(sep=', ', maxsplit=2))

출력:

['Apple', 'Banana, Orange, Blueberry']
['Apple', 'Banana', 'Orange, Blueberry']

str.splitlines(keepends=False): 有时我们想处理一个在边界处具有不同换行符('n'、nn'、'r'、'rn')的语料库。我们要拆分成句子,而不是单个单词。可以使用 splitline 方法来执行此操作。当 keepends=True 时,文本中包含换行符;否则它们被排除在外

import nltk# You may have to `pip install nltk` to use this library.
macbeth = nltk.corpus.gutenberg.raw('shakespeare-macbeth.txt')
print(macbeth.splitlines(keepends=True)[:5]

Output:

['[The Tragedie of Macbeth by William Shakespeare 1603]n', 'n', 'n', 'Actus Primus. Scoena Prima.n', 'n']

str.strip([chars]): 我们使用 strip 方法从字符串的两侧删除尾随空格或字符。例如:

string = "Apple Apple Apple no apple in the box apple apple "
stripped_string = string.strip()
print(stripped_string)
left_stripped_string = (
stripped_string
.lstrip('Apple')
.lstrip()
.lstrip('Apple')
.lstrip()
.lstrip('Apple')
.lstrip()
)
print(left_stripped_string)
capitalized_string = left_stripped_string.capitalize()
print(capitalized_string)
right_stripped_string = (
capitalized_string
.rstrip('apple')
.rstrip()
.rstrip('apple')
.rstrip()
)
print(right_stripped_string)

Output:

Apple Apple Apple no apple in the box apple apple
no apple in the box apple apple
No apple in the box apple apple
No apple in the box

在上面的代码片段中,我们使用了 lstrip 和 rstrip 方法,它们分别从字符串的左侧和右侧删除尾随空格或字符。我们还使用了 capitalize 方法,它将字符串转换为句子大小写str.zfill(width): zfill 方法用 0 前缀填充字符串以获得指定的宽度。例如:

example = "0.8"# len(example) is 3
example_zfill = example.zfill(5) # len(example_zfill) is 5
print(example_zfill)

Output:

000.8

str.isalpha(): 如果字符串中的所有字符都是字母,该方法返回True;否则返回 False:

# Alphabet string
alphabet_one = "Learning"
print(alphabet_one.isalpha())
# Contains whitspace
alphabet_two = "Learning Python"
print(alphabet_two.isalpha())
# Contains comma symbols
alphabet_three = "Learning,"
print(alphabet_three.isalpha())

Output:

True
False
False

如果字符串字符是字母数字,str.isalnum() 返回 True;如果字符串字符是十进制,str.isdecimal() 返回 True;如果字符串字符是数字,str.isdigit() 返回 True;如果字符串字符是数字,则 str.isnumeric() 返回 True

如果字符串中的所有字符都是小写,str.islower() 返回 True;如果字符串中的所有字符都是大写,str.isupper() 返回 True;如果每个单词的首字母大写,str.istitle() 返回 True:

# islower() example
string_one = "Artificial Neural Network"
print(string_one.islower())
string_two = string_one.lower()# converts string to lowercase
print(string_two.islower())
# isupper() example
string_three = string_one.upper() # converts string to uppercase
print(string_three.isupper())
# istitle() example
print(string_one.istitle())

Output:

False
True
True
True

str.endswith(suffix) 返回 True 是以指定后缀结尾的字符串。如果字符串以指定的前缀开头,str.startswith(prefix) 返回 True:

sentences = ['Time to master data science', 'I love statistical computing', 'Eat, sleep, code']
# endswith() example
for one_sentence in sentences:
print(one_sentence.endswith(('science', 'computing', 'Code')))

Output:

True
True
False
# startswith() example
for one_sentence in sentences:
print(one_sentence.startswith(('Time', 'I ', 'Ea')))

Output:

True
True
True

str.find(substring) 如果子字符串存在于字符串中,则返回最低索引;否则它返回 -1。str.rfind(substring) 返回最高索引。如果找到,str.index(substring) 和 str.rindex(substring) 也分别返回子字符串的最低和最高索引。如果字符串中不存在子字符串,则会引发 ValueError

string = "programming"
# find() and rfind() examples
print(string.find('m'))
print(string.find('pro'))
print(string.rfind('m'))
print(string.rfind('game'))
# index() and rindex() examples
print(string.index('m'))
print(string.index('pro'))
print(string.rindex('m'))
print(string.rindex('game'))

Output:

6
0
7
-1
6
0
7
---------------------------------------------------------------------------
ValueErrorTraceback (most recent call last)
~AppDataLocalTemp/ipykernel_11336/3954098241.py in
 11 print(string.index('pro'))# Output: 0
 12 print(string.rindex('m'))# Output: 7
---> 13 print(string.rindex('game'))# Output: ValueError: substring not found
ValueError: substring not found

str.maketrans(dict_map) 从字典映射创建一个翻译表,str.translate(maketrans) 用它们的新值替换翻译中的元素。例如:

example = "abcde"
mapped = {'a':'1', 'b':'2', 'c':'3', 'd':'4', 'e':'5'}
print(example.translate(example.maketrans(mapped)))

Output:

12345

字符串操作

循环遍历一个字符串

字符串是可迭代的,因此它们支持使用 for 循环和枚举的循环操作:

# For-loop example
word = "bank"
for letter in word:
print(letter)

Output:

b
a
n
k
# Enumerate example
for idx, value in enumerate(word):
print(idx, value)

Output:

0 b
1 a
2 n
3 k

字符串和关系运算符

当使用关系运算符(>、

print('a' > 'b')
print('abc' > 'b')

Output:

False
False

在这两种情况下,输出都是 False。关系运算符首先比较两个字符串的索引 0 上元素的 ASCII 十进制数。由于 b 大于 a,因此返回 False;在这种情况下,其他元素的 ASCII 十进制数字和字符串的长度无关紧要

当字符串长度相同时,它比较从索引 0 开始的每个元素的 ASCII 十进制数,直到找到具有不同 ASCII 十进制数的元素。例如:

print('abd' > 'abc')

Output:

True

检查字符串的成员资格

in 运算符用于检查子字符串是否是字符串的成员:

print('data' in 'dataquest')
print('gram' in 'programming')

Output:

True
True

检查字符串成员资格、替换子字符串或匹配模式的另一种方法是使用正则表达式

import re
substring = 'gram'
string = 'programming'
replacement = '1234'
# Check membership
print(re.search(substring, string))
# Replace string
print(re.sub(substring, replacement, string))

Output:

pro1234ming

字符串格式

f-string 和 str.format() 方法用于格式化字符串。两者都使用大括号 {} 占位符。例如:

monday, tuesday, wednesday = "Monday", "Tuesday", "Wednesday"
format_string_one = "{} {} {}".format(monday, tuesday, wednesday)
print(format_string_one)
format_string_two = "{2} {1} {0}".format(monday, tuesday, wednesday)
print(format_string_two)
format_string_three = "{one} {two} {three}".format(one=tuesday, two=wednesday, three=monday)
print(format_string_three)
format_string_four = f"{monday} {tuesday} {wednesday}"
print(format_string_four)

Output:

Monday Tuesday Wednesday
Wednesday Tuesday Monday
Tuesday Wednesday Monday
Monday Tuesday Wednesday

f-strings 更具可读性,并且它们比 str.format() 方法实现得更快。因此,f-string 是字符串格式化的首选方法

处理引号和撇号

撇号 (') 在 Python 中表示一个字符串。为了让 Python 知道我们不是在处理字符串,我们必须使用 Python 转义字符 ()。因此撇号在 Python 中表示为 '。与处理撇号不同,Python 中有很多处理引号的方法。它们包括以下内容:

# 1. Represent string with single quote (`""`) and quoted statement with double quote (`""`)
quotes_one ='"Friends don't let friends use minibatches larger than 32" - Yann LeCun'
print(quotes_one)
# 2. Represent string with double quote `("")` and quoted statement with escape and double quote `("statement")`
quotes_two =""Friends don't let friends use minibatches larger than 32" - Yann LeCun"
print(quotes_two)
# 3. Represent string with triple quote `("""""")` and quoted statment with double quote ("")
quote_three = """"Friends don't let friends use minibatches larger than 32" - Yann LeCun"""
print(quote_three)

Output:

"Friends don't let friends use minibatches larger than 32" - Yann LeCun
"Friends don't let friends use minibatches larger than 32" - Yann LeCun
"Friends don't let friends use minibatches larger than 32" - Yann LeCun

写在最后

字符串作为编程语言当中最为常见的数据类型,熟练而灵活的掌握其各种属性和方法,实在是太重要了,小伙伴们千万要实时温习,处处留心哦!

好了,这就是今天分享的内容,如果喜欢就点个赞吧~

위 내용은 파이썬 문자열 요약, 모아두는 걸 추천!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 51cto.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제