Strings Flashcards
x = “,,,,,rrttgg…..banana….rrr”
return banana
using strip method
txt = “,,,,,rrttgg…..banana….rrr”
x = txt.strip(“,.grt”)
print(x)
x = a_string = ‘!hi. wh?at is the weat[h]er lik?e.’
return hi what is the weather like
using maketrans() method
import string
a_string = ‘!hi. wh?at is the weat[h]er lik?e.’
new_string = a_string.translate(str.maketrans(‘’, ‘’, string.punctuation))
print(new_string)
Returns: hi what is the weather like
‘Smart developers create their script in a text editor.’
Number of words
txt = ‘Smart developers create their script in a text editor.’
words = txt.split()
print(len(words))
Check if “free” is present in the following text:
txt = “The best things in life are free!”
print(“free” in txt)
Print only if “free” is present
txt = “The best things in life are free!”
if “free” in txt:
print(“Yes, ‘free’ is present.”)
Get the characters from the start to position 5 (not included):
b = “Hello, World!”
print(b[:5])
Get the characters from position 2, and all the way to the end:
b = “Hello, World!”
print(b[2:])
Get the characters:
From: “o” in “World!” (position -5)
To, but not included: “d” in “World!” (position -2):
b = “Hello, World!”
print(b[-5:-2])
The upper() method returns the string in upper case and lower () to return lower case.
a = “Hello, World!”
print(a.upper())
print(a.lower())
The strip() method removes any whitespace from the beginning or the end:
a = “ Hello, World! “
print(a.strip()) # returns “Hello, World!”
The replace() method replaces a string with another string:
a = “ Hello, World! “
print(a.replace(“H”, “J”))
The split() method splits the string into substrings if it finds instances of the separator:
a = “Hello, World!”
# returns [‘Hello’, ‘ World!’]
print(a.split(“,”))
quantity = 3
itemno = 567
price = 49.95
myorder = “I want {} pieces of item {} for {} dollars.”
Use format () method
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49.95
myorder = ?????? What to put here?
print(myorder.format(quantity, itemno, price))
myorder = “I want to pay {2} dollars for {0} pieces of item {1}.”
Print the longest word and the number of its digit of a sentence:
‘Mondok egy tök hosszú mondatot, elfelejtettem a számot is’
txt=input(‘pleas provide a sentence: ‘)
szavak=txt.split
longest_word = max(szavak, key=len)
longest_word_length = len(longest_word)
print(f’A leghosszabb szó {longest_word} és {longest_word_length} karakterből áll. ‘)