строки_python

Строки Python

Работа с fString в Python

name = "nevvad"
print(f"My name is {name}") # My name is nevvad
print(len(name)) # 6
 
######
first_name = "John"
second_name = "Doe"
 
sentence = 'My name  is {} {}'.format(first_name, second_name)
print(sentence) # My name  is John Doe
 
sentence = f'My name  is {first_name} {second_name}'
print(sentence) # My name  is John Doe
 
sentence = f'My name  is {first_name.upper()} {second_name.upper()}'
print(sentence) # My name  is JOHN DOE
 
######
person = {'name': 'Jane Doe', 'age': 40}
sentence = 'My name is {} and I am {} years old'.format(person['name'], person['age'])
print(sentence) # My name is Jane Doe and I am 40 years old
 
sentence = f'My name is {person["name"]} and I am {person["age"]} years old'
print(sentence) # My name is Jane Doe and I am 40 years old
 
######
calculation = f'4 times 11 is equal to {4 * 11}'
print(calculation) # 4 times 11 is equal to 44
 
######
for n in range(1, 11):
    sentence = f'The value is {n}' # Output: The value is 1
    print(sentence)
 
for n in range(1, 11):
    sentence = f'The value is {n:04}' # Output: The value is 0001
    print(sentence)
 
######
pi = 3.14159265
sentence = f'Pi is equal to {pi:.4f}'
print(sentence) # Pi is equal to 3.1416
 
######
from datetime import datetime
birthday = datetime(1982, 1, 1)
 
sentence = f'Jane Doe has a birthday on {birthday}'
print(sentence) # Jane Doe has a birthday on 1982-01-01 00:00:00
 
sentence = f'Jane Doe has a birthday on {birthday:%B %d, %Y}'
print(sentence) # Jane Doe has a birthday on January 01, 1982

Более подробно, о форматирование дат, можно прочесть в параграфе 8.1.8. strftime официальной документации.

  • строки_python.txt
  • Последнее изменение: 2022/11/16 15:41
  • admin