Python. f-strings

Python. f-strings

Any string is a sequence of characters enclosed in quotes.

For example, "School", 'Python', 'Computer science', "123".

Since version Python 3.6, developers have implemented a new type of string - f-strings or formatted strings, which are not only faster than other formatting methods but also improve code readability.
When writing a formatted string, the quotation marks are preceded by a format character, the letter f

For example,

f"Python", f'Sum = {sum}'.

Examples of using:

print('Hello, world!')  # simple string
print(f'Hello, world!')  # formatted string


name = "Arman"
age = 16
print("My name is ", name, ". I am ", age, " years old.", sep='')
# My name is Arman. I am 16 years old.
print(f"My name is {name}. I am {age} years old.")
# My name is Arman. I am 16 years old.
print(f"My name is {name.upper()}. I am {age} years old.")
# My name is ARMAN. I am 16 years old.


daysofweek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
             'Friday', 'Saturday', 'Sunday']
print(f"The 5th day of week - {daysofweek[4]}") # The 5th day of week - Friday


x = 10
y = 3
print(f"({x} + {y}) ** 2 = {(x + y) ** 2}") # (10 + 3) ** 2 = 169


print(f"50 // 8 = {round(50/8)}")  # 50 // 8 = 6


print(f"Real number with two digits after point - {(38/6):.2f}")
# Real number with two digits after point - 6.33


print(f"Percentage of number - {(73/87):.2%}")
# Percentage of number - 83.91%


print(f"180 in binary - {(180):b}") # 180 in binary - 10110100
print(f"180 in hexadecimal - {(180):x}") # 180 in hexadecimal - b4
print(f"180 in octal - {(180):o}") # 180 in octal - 264


table = ['Lunara', 'Ruslan', 'Alua']
for name in table:
   print(f'{name:10}')
print()
table2 = [4142, 3098, 5678]
for num in table2:
   print(f'{num:10}')

# Lunara....    
# Ruslan....
# Alua......
#

# ......4142
# ......3098
# ......5678


print(f'Number Square   Cube')
for x in range(1, 11):
   print(f'{x:6d} {x*x:6d} {x*x*x:6d}')

Questions:

Exercises:

Tasks:

 

 

Категория: Programming languages | Добавил: bzfar77 (20.01.2022)
Просмотров: 2271 | Теги: Output, formatted string, Python, String | Рейтинг: 5.0/1
Всего комментариев: 0
avatar