توابع sscanf() پایتون

مثال

پارس کردن رشته:

<?php
$str = "age:30 weight:60kg";
sscanf($str,"age:%d weight:%dkg",$age,$weight);
// نمایش نوع و ارزش
var_dump($age,$weight);
?>

Run Instances

تعریف و استفاده

تابع sscanf() ورودی‌های موجود در رشته را بر اساس فرمت مشخص می‌کند. تابع sscanf() بر اساس رشته فرمت به متغیرها پارس می‌کند.

اگر تنها دو پارامتر به این تابع ارسال شود، داده‌ها به صورت یک آرایه بازگردانده می‌شوند. در غیر این صورت، اگر پارامترهای اضافی ارسال شوند، داده‌های پارس شده در این پارامترها ذخیره می‌شوند. اگر تعداد کاراکترهای جداکننده بیشتر از تعداد متغیرهایی که شامل آنها هستند باشد، خطا رخ می‌دهد. اما اگر تعداد کاراکترهای جداکننده کمتر از تعداد متغیرهایی که شامل آنها هستند باشد، متغیرهای اضافی NULL را شامل می‌شوند.

تابعهای مرتبط:

  • printf() - چاپ یک رشته فرمت شده
  • sprintf() - نوشتن یک رشته فرمت شده به یک متغیر

نحوه استفاده

sscanf(string,format,arg1,arg2,arg++)
پارامتر توضیح
string ضروری. تعیین رشته‌ای که باید خوانده شود.
format

ضروری. تعیین فرمتی که باید استفاده شود.

ممکنه ارزشهای فرمت:

  • %% - بازگشت یک درصد %
  • %c - کاراکتر مرتبط با کد ASCII
  • %d - عدد اعشاری با نشانه مثبت یا منفی (عدد منفی، 0، عدد مثبت)
  • %e - استفاده از شمارش علمی با حروف کوچک (مثلاً 1.2e+2)
  • 誒دد اعشاری بدون نشانه مثبت یا منفی (بزرگتر یا برابر با 0)
  • %f - عدد اعشاری
  • %o - عدد هشتادسانی
  • %s - رشته
  • %x - شماره شانسی (حروف کوچک)
  • %X - Hexadecimal number (uppercase letters)}

Additional format values. Must be placed between % and the letter (for example, %.2f):

  • + (adds + or - in front of the number to define the sign of the number. By default, only negative numbers are marked, and positive numbers are not marked.)
  • ' (specifies what to use as padding, default is space. It must be used with the width specifier.)
  • - (left-justifies the variable value)
  • .[0-9] (specifies the minimum width of the variable value)
  • .[0-9] (specifies the number of decimal places or the maximum string length)

Note:If multiple of the above format values are used, they must be used in the order listed above.

arg1 Optional. The first variable storing data.
arg2 Optional. The second variable storing data.
arg++ Optional. The third, fourth variables storing data, and so on.

Technical Details

Return Value: If only two parameters are passed to this function, the data will be returned in array form. Otherwise, if additional parameters are passed, the parsed data will be stored in these parameters. If the number of delimiters is greater than the number of variables containing them, an error will occur. However, if the number of delimiters is less than the number of variables containing them, the additional variables will contain NULL.
PHP Version: 4.0.1+

More Examples

Example 1

Use format values %s, %d, and %c:

<?php
$str = "If you divide 4 by 2 you'll get 2";
$format = sscanf($str,"%s %s %s %d %s %d %s %s %c");
print_r($format);
?>

Run Instances