"A string is a sequence of characters."
Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0's and 1's.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encoding used.
In Python, string is a sequence of Unicode character.
Подробнее о юникоде
https://docs.python.org/3.3/howto/unicode.html
Как создать строку?
Строки можно создавать, заключая символы в одинарные или двойные кавычки.
В Python можно использовать даже тройные кавычки, но обычно они используются для представления многострочных строк и строк документации.
[4]:
myString = 'Hello' print(myString) myString = "Hello" print(myString) myString = '''Hello''' print(myString) Hello Hello Hello
Как получить доступ к символам в строке?
Мы можем получить доступ к отдельным символам, используя индексацию, и ряду символов, используя нарезку.
Индекс начинается с 0.
Попытка доступа к символу вне диапазона индекса вызовет ошибку IndexError.
Индекс должен быть целым числом. Мы не можем использовать float или другие типы, это приведет к TypeError.
Python допускает отрицательное индексирование своих последовательностей.
[5]:
myString = "Hello" #print first Character print(myString[0]) #print last character using negative indexing print(myString[-1]) #slicing 2nd to 5th character print(myString[2:5]) H o llo
Если мы попытаемся получить доступ к индексу вне диапазона или использовать десятичное число, мы получим ошибки.
[6]:
print(myString[15]) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-6-a6e04654a783> in <module> ----> 1 print(myString[15]) IndexError: string index out of range
[7]:
print(myString[1.5]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-f317be76d762> in <module> ----> 1 print(myString[1.5]) TypeError: string indices must be integers
Как изменить или удалить строку?
Строки неизменяемы. Это означает, что элементы строки не могут быть изменены после того, как они были назначены.
Мы можем просто переназначить разные строки одному и тому же имени.
[8]:
myString = "Hello"
myString[4] = 's' # strings are immutable
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-786fea0a1f9c> in <module>
1 myString = "Hello"
----> 2 myString[4] = 's' # strings are immutable
TypeError: 'str' object does not support item assignment
Мы не можем удалять или удалять символы из строки. Но полное удаление строки возможно с помощью ключевого слова del.
[9]:
del myString # delete complete string
[10]:
print(myString) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-10-13235c81a0c6> in <module> ----> 1 print(myString) NameError: name 'myString' is not defined
Строковые операции
Конкатенация
Объединение двух или более строк в одну называется конкатенацией.
Оператор + делает это в Python. Простое написание двух строковых литералов вместе также объединяет их.
Оператор * может использоваться для повторения строки заданное количество раз.
[11]:
s1 = "Hello " s2 = "Satish" #concatenation of 2 strings print(s1 + s2) #repeat string n times print(s1 * 3) Hello Satish Hello Hello Hello
Итерация по строке
[12]:
count = 0 for l in "Hello World": if l == 'o': count += 1 print(count, ' letters found') 2 letters found
Тест на принадлежность к строке
[13]:
print('l' in 'Hello World') #in operator to test membership
True
[14]:
print('or' in 'Hello World')
True
Строковые методы
Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace() etc
[15]:
"Hello".lower()
[15]:
'hello'
[16]:
"Hello".upper()
[16]:
'HELLO'
[17]:
"This will split all words in a list".split()
[17]:
['This', 'will', 'split', 'all', 'words', 'in', 'a', 'list']
[18]:
' '.join(['This', 'will', 'split', 'all', 'words', 'in', 'a', 'list'])
[18]:
'This will split all words in a list'
[19]:
"Good Morning".find("Mo")
[19]:
5
[20]:
s1 = "Bad morning"
s2 = s1.replace("Bad", "Good")
print(s1)
print(s2)
Bad morning
Good morning
Программа Python для проверки того, где строка является палиндромом или нет?
[21]:
myStr = "Madam"
#convert entire string to either lower or upper
myStr = myStr.lower()
#reverse string
revStr = reversed(myStr)
#check if the string is equal to its reverse
if list(myStr) == list(revStr):
print("Given String is palindrome")
else:
print("Given String is not palindrome")
Given String is palindrome
Программа Python для сортировки слов в алфавитном порядке?
[22]:
myStr = "python Program to Sort words in Alphabetic Order" #breakdown the string into list of words words = myStr.split() #sort the list words.sort() #print Sorted words are for word in words: print(word) Alphabetic Order Program Sort in python to words