Pythonでフォーマットされた文字列リテラル(f-strings)?
Pythonは、f-stringsと呼ばれる文字列をフォーマットする新しい方法を提供するようになりました。この機能は、PEP-498のPython3.6から利用できます。文字列の接頭辞「f」が付いているため、これらは(f-string)と呼ばれます。文字「f」は、これらのf文字列をフォーマットに使用できることも示します。
以下は、f文字列の使用法を示す例の一部です。
プログラム#1
name = 'Rajesh'
age = 13 * 3
fString = f'My name is {name} and my age is {age}'
print(fString)
#We can use Uppercase 'F' instead of lowercase 'f'.
print(F'My name is {name} and my age is {age}')
#As the fString valuation is done, giving another value to the variable will not change fstring value.
name = 'Zack'
age = 44
print(fString) 出力
My name is Rajesh and my age is 39 My name is Rajesh and my age is 39 My name is Rajesh and my age is 39
例#2 –式と変換を含むf文字列
日時からインポート日時
name = 'Rajesh'
age = 13 * 3
dt = datetime.now()
print(f' Age after ten years will be {age + 10}')
print(f'Name with quotes = {name!r}')
print(f'Default formatted Date = {dt}')
print(f'Modified Date format = {dt: %d/%m/%Y}') 出力
Age after ten years will be 49 Name with quotes = 'Rajesh' Default formatted Date = 2019-02-11 14:52:05.307841 Modified Date format = 11/02/2019
例#3:オブジェクトと属性
class Vehicle:
Model = 0
Brand = ''
def __init__(self, Model, Brand):
self.Model = Model
self.Brand = Brand
def __str__(self):
return f'E[Model={self.Model}, Brand = {self.Brand}]'
Car = Vehicle (2018, 'Maruti')
print(Car)
print(f'Vehicle: {Car}\nModel is {Car.Model} and Brand is {Car.Brand}') 出力
E[Model=2018, Brand = Maruti] Vehicle: E[Model=2018, Brand = Maruti] Model is 2018 and Brand is Maruti
例#4:関数の呼び出し
f文字列形式で関数を呼び出すこともできます。
def Multiply(x,y):
return x*y
print( f'Multiply(40,20) = {Multiply(40,20)}') 出力
Multiply(40,20) = 800
例#5:ラムダ式
x = -40.9
print(f' Lambda absolute of (-40.9) is : {(lambda x: abs(x)) (x)}')
print(f' Lambda Square of 2^4 is: {(lambda x: pow(x, 2)) (4)}') 出力
Lambda absolute of (-40.9) is : 40.9 Lambda Square of 24 is: 16
-
Pythonで文字列を逆にする
文字の配列があるとします。追加のスペースを使用せずに文字列を反転する必要があります。したがって、文字列が[H、E、L、L、O]のような場合、出力は[O、L、L、E、 H] これを解決するには、次の手順に従います- 2つのポインタを使用して、開始=0および終了=文字列の長さ– 1 最初と最後の文字を入れ替える 開始を1増やし、終了を1減らします 例 理解を深めるために、次の実装を見てみましょう- class Solution(object): def reverseString(self, s): "&q
-
Pythonのcasefold()文字列
この関数は、単語の文字を小文字に変換するのに役立ちます。 2つの文字列に適用すると、文字の大文字小文字の種類に関係なく、それらの値と一致する可能性があります。 casefold()の適用 以下の例では、casefold()関数を文字列に適用すると、結果はすべて小文字で出力されます。 例 string = "BestTutorials" # print lowercase string print(" lowercase string: ", string.casefold()) 出力 上記のコードを実行すると、次の結果が得られます- Lowerca