Сегодня мы узнаем о строковых функциях
До сих пор мы использовали строки для различных программ. Мы использовали их как в качестве входных и выходных параметров. Но теперь мы узнаем, как их изменять. На этой неделе мы будем делать операции, как разбить предложение словами, сломать строки в письма, заглавят их без использования Орд () взломать или подсчитать количество гласных в предложении.
Строка в виде списка
В Python мы можем легко интерпретировать строку как список символов. В приведенном ниже примере мы можем применить Лен () Функция на строку TXT или итерации для цикла. Но мы не можем рассматривать его как список и выполнять такие опор, как POP или Append ()
#Interpreting the string as an array of characters.
txt= "Python"
print(txt)
print("Length of the txt = ", len(txt))
#display string using in keyword
for ch in txt:
print(ch)
#display the string in original form using range()
for ch in range(0, len(txt)):
print(txt[ch], end=" ")
print()
#to display in reverse order
for ch in range(len(txt)-1, -1 , -1):
print(txt[ch], end="")
#We cannot append a character or pop using the standered length functions.
txt.append("a")
print(txt)
ВЫХОД-
Python Length of the txt = 6 P y t h o n P y t h o n nohtyPTraceback (most recent call last): File "C:/Users/aatma/Downloads/Example 1 .py", line 21, intxt.append("a") AttributeError: 'str' object has no attribute 'append'
Изменение дела
Теперь мы увидим, как обрабатывать верхние и мелкие случаи в Python без какого-либо прямого использования символов Unicode.
#1. Upper case the first letter in this sentence: txt = "hello, AND Welcome" x = txt.capitalize() print (x) #output : Hello, and welcome #2. Make the string lower case: txt = "Hello, And Welcome!@#$" x = txt.lower() print (x) #output : hello, and welcome #3. Make the string upper case: txt = "Hello, And Welcome" x = txt.upper() print (x) #output : HELLO, AND WELCOME
ВЫХОД-
Hello, and welcome hello, and welcome!@#$ HELLO, AND WELCOME
Слово определенные методы
Теперь давайте посмотрим на более строковые функции через программу. Комментарии там, когда это необходимо.
#1.Print the word "computer", taking up the space of 25 characters,
#with "computer" in the middle:
txt = "computer"
x = txt.center(25)
print ("hello",x,"world")
# 2 default spaces+25 total characters. so distance between hello and world must be 27 characters.
#2. Return the number of times the value "act" appears in the string:
txt = "I love programming, programming is my favorite activity"
print(txt)
x = txt.count('i')
print ("Frequency of the value =" , x)
#case matters. Capital I and small i are treated differently.
#3. Check if the string ends with a punctuation sign .
txt = "Hello, welcome to my world."
x = txt.endswith("my world.")
print(x)
#4. Set the tab size to 5 whitespaces:
print("First\tsecond")
txt1 = "ACADEMY"
txt = "A\tC\tA\tDE\tM Y" # backslah t (i.e. \t) represents tab space.
x = txt.expandtabs(6) #expands the tab spaces
print(x)
#5. Locates the word "welcome" in the string and returns the index:
txt = "Hello, welcome to my world."
print(txt)
x = txt.find("welcome")
print(x)
#output : 7
#if the result is -1, string does not exist in the sentence
ВЫХОД-
hello computer world I love programming, programming is my favorite activity Frequency of the value = 6 True First second A C A DE M Y Hello, welcome to my world. 7
Упражнения
1) – Напишите программу, чтобы изменить капитализацию ввода пользователя и добавить полную остановку в конце, если она не присутствует.
Please enter a string: a QUick Brown FOX jumps OVer the Lazy doG A quick brown fox jumps over the lazy dog.
2) – Напишите программу, чтобы дать следующий вывод
Please enter a string: Python P P y P y t P y t h P y t h o P y t h o n
Оригинал: “https://dev.to/aatmaj/learning-python-basic-course-day-22-string-methods-part-1-9j8”