String Formatting कैसे करें
String formatting एक template को एक set style में values से भरता है, stamped blanks वाले एक form letter की तरह। आप जो दिखता है इसके decimals और width control कर सकते हैं।
In this page:
Syntax
format("%s is %d years old", string_value, integer_value)
"%.2f" % decimal_value
String Formatting
% operator (या format/sprintf methods) %s, %d, और %.2f जैसे format specifiers इस्तेमाल करते हुए एक string में values format करता है, C के printf जैसा।
यह plain interpolation से output पर ज़्यादा precise control देता है, जैसे fixed decimal places या zero-padding। format और sprintf same underlying behavior के लिए aliases हैं।
Note:
format("%.2f", value) एक number को exactly 2 decimal places तक format करने का standard तरीका है।उदाहरण: String Formatting
name = "Alice"
score = 92.567
puts format("Name: %s, Score: %.2f", name, score)
puts "Padded: %05d" % 42
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- एक decimal value के साथ
%dइस्तेमाल करना और rounding की उम्मीद करना, जब यह truncate करता है। - कई specifiers के साथ
%को एक array की बजाय एक single argument pass करना, जैसे"%s %s" % "a", जोArgumentErrorraise करता है। - एक literal percent sign के लिए
%%भूल जाना।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: