Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
Базові Операції з Рядками
Строки - це частини тексту. Вони можуть бути визначені будь-яким текстом всередині лапок:
astring = "Hello world!"
astring2 = 'Hello world!'
Як бачите, перше, що ви навчилися, це друкувати просте речення. Це речення було збережене Python як строка. Однак, замість негайного виведення строк, ми дослідимо різні речі, які ви можете з ними робити. Ви також можете використовувати одинарні лапки для призначення строки. Однак, у вас виникнуть проблеми, якщо значення, яке потрібно призначити, саме містить одинарні лапки. Наприклад, щоб призначити строку в цих дужках (одинарні лапки ' '), необхідно використовувати лише подвійні лапки, як ось так:
astring = "Hello world!"
print("single quotes are ' '")
print(len(astring))
Це виводить 12, оскільки "Hello world!" має 12 символів, включаючи пунктуацію та пробіли.
astring = "Hello world!"
print(astring.index("o"))
Це виводить 4, оскільки розташування першого входження літери "o" знаходиться на 4 символи від першого символу. Зверніть увагу, що насправді в фразі два "o" - цей метод розпізнає лише перше.
Але чому ж не 5? Хіба "o" не п'ятий символ у рядку? Щоб спростити речі, Python (та більшість інших мов програмування) починає з 0, а не з 1. Тому індекс "o" - це 4.
astring = "Hello world!"
print(astring.count("l"))
Для тих, хто використовує дивні шрифти, це маленька літера "l", а не цифра один. Це рахує кількість букв "l" у рядку. Отже, це має вивести 3.
astring = "Hello world!"
print(astring[3:7])
Це виводить частину рядка, починаючи з індекса 3 і закінчуючи індексом 6. Але чому 6, а не 7? Знову ж таки, більшість мов програмування роблять це - це спрощує виконання математики всередині цих дужок.
Якщо у вас є лише одне число в дужках, це дасть вам єдиний символ за цим індексом. Якщо ви пропустите перше число, але залишите двокрапку, ви отримаєте частину рядка від початку до числа, яке залишили. Якщо ви пропустите друге число, вам буде надано частину рядка від першого номера до кінця.
Ви навіть можете поміщати від'ємні числа всередину дужок. Це легкий спосіб починати з кінця рядка, замість початку. Таким чином, -3 означає "3-й символ з кінця".
astring = "Hello world!"
print(astring[3:7:2])
Це виводить символи рядка від 3 до 7, пропускаючи один символ. Це розширений синтаксис зрізу. Загальна форма - [start:stop:step].
astring = "Hello world!"
print(astring[3:7])
print(astring[3:7:1])
Зверніть увагу, що обидва дають такий самий вихід.
У C немає такої функції, як strrev, щоб перевернути строку. Але за допомогою вищезгаданого синтаксису зрізу ви можете легко перевернути строку, як ось так:
astring = "Hello world!"
print(astring[::-1])
Це
astring = "Hello world!"
print(astring.upper())
print(astring.lower())
Ці функції створюють новий рядок із усіма літерами, переведеними у верхній та нижній регістр відповідно.
astring = "Hello world!"
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))
Це використовується для визначення того, чи рядок починається з чого-небудь або закінчується на щось відповідно. Перше виведе True, оскільки рядок починається з "Hello". Друге виведе False, оскільки рядок, безумовно, не закінчується на "asdfasdfasdf".
astring = "Hello world!"
afewwords = astring.split(" ")
Це розбиває рядок на купу рядків, згрупованих разом у список. Оскільки цей приклад розбиває на пробіл, першим елементом у списку буде "Hello", а другим - "world!".
Exercise
Спробуйте виправити код, щоб вивести правильну інформацію, змінивши строку.
s = "Hey there! what should this string be?"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))
s = "Strings are awesome!"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))
test_object("s", incorrect_msg="Make sure you change the string assigned to `s` to match the exercise instructions.")
success_msg("Great work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!