← Back to Perl Course | Chapter 3: Strings | Lesson 7 of 7

sprintf और printf

sprintf एक formatted string बनाता है, और printf इसे सीधे print करता है।

In this page:

  1. sprintf और printf

sprintf और printf

Format string में conversion codes होते हैं जैसे strings के लिए %s, integers के लिए %d, floating-point numbers के लिए %f, और hexadecimal के लिए %x। आप एक width, %.2f जैसी एक precision, left alignment के लिए एक minus sign, और zero padding के लिए एक 0 add कर सकते हैं। printf formatted result print करता है, जबकि sprintf इसे return करता है ताकि आप इसे store कर सकें।

Note: एक literal percent sign print करने के लिए %% लिखें।

उदाहरण: sprintf and printf

perl
use strict;
use warnings;

my $pi = 3.14159265;
printf "Pi to 2 places: %.2f\n", $pi;
printf "Integer from float: %d\n", 7.9;
printf "Padded: [%5d] [%-5d] [%05d]\n", 42, 42, 42;
printf "Strings: [%8s] [%-8s]\n", "right", "left";
printf "Hex: %x, Octal: %o, Binary: %b\n", 255, 8, 5;
printf "Percent: %d%%\n", 50;
my $row = sprintf("%-10s|%6.1f", "Total", 1234.567);
print "$row\n";
print "Scientific: ", sprintf("%.3e", 12345.678), "\n";

# Output:
# Pi to 2 places: 3.14
# Integer from float: 7
# Padded: [   42] [42   ] [00042]
# Strings: [   right] [left    ]
# Hex: ff, Octal: 10, Binary: 101
# Percent: 50%
# Total     |1234.6
# Scientific: 1.235e+04
{# 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. #}
आम गलतियां
  1. conversion codes से कम arguments supply करना
  2. एक fractional number के साथ %d इस्तेमाल करना और rounding की उम्मीद करना
  3. यह भूल जाना कि printf एक newline add नहीं करता
चैप्टर सारांश
  • %s string, %d integer, %f float को represent करते हैं
  • %.2f precision set करता है
  • Width और flags align और pad करते हैं
  • sprintf return करता है और printf print करता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.