<!DOCTYPE html>
    <html lang="vi" xmlns="http://www.w3.org/1999/xhtml" prefix="og: http://ogp.me/ns#">
    <head>
<title>Hàm str&#40;&#41; trong Python</title>
<meta name="description" content="Hàm str&#40;&#41; trong Python - Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;ham-str-trong-python-9856.html">
<meta name="author" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :.">
<meta name="copyright" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :. [admin@nguoicodonvn2008.info]">
<meta name="robots" content="index, archive, follow, noodp">
<meta name="googlebot" content="index,archive,follow,noodp">
<meta name="msnbot" content="all,index,follow">
<meta name="generator" content="NukeViet v4.5">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta property="og:title" content="Hàm str&#40;&#41; trong Python">
<meta property="og:type" content="website">
<meta property="og:description" content="Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;ham-str-trong-python-9856.html">
<meta property="og:site_name" content=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.">
<meta property="og:url" content="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/ham-str-trong-python-9856.html">
<link rel="shortcut icon" href="https://nguoicodonvn2008.info/favicon.ico">
<link rel="canonical" href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/ham-str-trong-python-9856.html">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/" title="Tin Tức" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/karaoke-dual/" title="Tin Tức - Karaoke Dual" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/nhac-tre/" title="Tin Tức - Nhạc trẻ" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/tru-tinh/" title="Tin Tức - Trữ tình" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/nuoc-ngoai/" title="Tin Tức - Nước ngoài" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/remix/" title="Tin Tức - Remix" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/tam-su-tinh-yeu/" title="Tin Tức - Tâm sự tình yêu" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/tho-suu-tam/" title="Tin Tức - Thơ sưu tầm" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/cuoc-song/" title="Tin Tức - Cuộc sống" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/phan-mem/" title="Tin Tức - Phần mềm" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/kien-thuc-may-tinh/" title="Tin Tức - Kiến thức máy tính" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/hoc-tap/" title="Tin Tức - Học tập" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/tai-lieu/" title="Tin Tức - Tài liệu" type="application/rss+xml">
<link rel="alternate" href="https://nguoicodonvn2008.info/vi/news/rss/de-thi/" title="Tin Tức - Đề thi" type="application/rss+xml">
<link rel="preload" as="style" href="https://nguoicodonvn2008.info/assets/css/font-awesome.min.css" type="text/css">
<link rel="preload" as="style" href="https://nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://nguoicodonvn2008.info/themes/default/css/style.css" type="text/css">
<link rel="preload" as="style" href="https://nguoicodonvn2008.info/themes/default/css/style.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://nguoicodonvn2008.info/themes/default/css/news.css" type="text/css">
<link rel="preload" as="style" href="https://nguoicodonvn2008.info/themes/default/css/custom.css" type="text/css">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/assets/js/jquery/jquery.min.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/assets/js/language/vi.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/assets/js/global.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/assets/js/site.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/themes/default/js/news.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/themes/default/js/main.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/themes/default/js/custom.js" type="text/javascript">
<link rel="preload" as="script" href="https://nguoicodonvn2008.info/themes/default/js/bootstrap.min.js" type="text/javascript">
<link rel="stylesheet" href="https://nguoicodonvn2008.info/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="https://nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css">
<link rel="stylesheet" href="https://nguoicodonvn2008.info/themes/default/css/style.css">
<link rel="stylesheet" href="https://nguoicodonvn2008.info/themes/default/css/style.non-responsive.css">
<link rel="StyleSheet" href="https://nguoicodonvn2008.info/themes/default/css/news.css">
<link rel="stylesheet" href="https://nguoicodonvn2008.info/themes/default/css/custom.css">
<style type="text/css">
	body{background: #fff;}
</style>
    </head>
    <body>
<div id="print">
	<div id="hd_print">
		<h2 class="pull-left">.&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.</h2>
		<p class="pull-right"><a title=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;." href="https://nguoicodonvn2008.info/">https://nguoicodonvn2008.info</a></p>
	</div>
	<div class="clear"></div>
	<hr />
	<div id="content">
		<h1>Hàm str&#40;&#41; trong Python</h1>
		<ul class="list-inline">
			<li>Thứ năm - 20/02/2025 22:55</li>
			<li class="hidden-print txtrequired"><em class="fa fa-print">&nbsp;</em><a title="In ra" href="javascript:;" onclick="window.print()">In ra</a></li>
			<li class="hidden-print txtrequired"><em class="fa fa-power-off">&nbsp;</em><a title="Đóng cửa sổ này" href="javascript:;" onclick="window.close()">Đóng cửa sổ này</a></li>
		</ul>
		<div class="clear"></div>
		<div id="hometext">
		</div>
				<div class="imghome">
			<img alt="Hàm str&#40;&#41; trong Python" src="https://st.quantrimang.com/photos/image/2020/06/29/ham-str-trong-python.jpg" width="460" class="img-thumbnail" />
		</div>
		<div class="clear"></div>
		<div id="bodytext" class="clearfix">
			<p style="text-align: justify;"><strong>str trong Python&nbsp;</strong>được dùng như thế nào?&nbsp;<strong>Cách dùng lệnh str trong Python&nbsp;</strong>có khó không? Hãy cùng nhau tìm hiểu nhé!</p>

<p style="text-align: justify;">Chuỗi là một kiểu lập trình cơ bản. Chúng là một chuỗi các ký tự chữ cái, số hoặc ký hiệu. Chuỗi Python thường được sử dụng khi xử lý văn bản, dữ liệu có cấu trúc hoặc dữ liệu từ các nguồn bên ngoài.</p>

<p style="text-align: justify;">Vì vậy, nếu bạn muốn bắt đầu lập trình bằng Python, bạn cần biết cách xử lý chúng. Chuỗi không thể thay đổi, nghĩa là sau khi tạo, chúng không thể bị sửa đổi. Tuy nhiên, chúng có thể được thao tác bằng nhiều phương pháp khác nhau. Hãy cùng tìm hiểu về chuỗi hay lệnh str trong Python nhé!</p>

<h2 style="text-align: justify;">Chuỗi trong Python là gì?</h2>

<p style="text-align: justify;">Chuỗi Python có thể được định nghĩa theo nhiều cách khác nhau: dấu ngoặc đơn hoặc dấu ngoặc kép, nhưng cũng có thể là 3 dấu ngoặc. Sử dụng ba dấu ngoặc đơn hoặc ba dấu ngoặc kép cho phép tính đến ngắt dòng khi hiển thị chuỗi.</p>

<p style="text-align: justify;">Bạn có thể gán một chuỗi Python cho một biến để tối ưu hóa mã của mình và tránh quá tải nó bằng các chuỗi dài sẽ lặp lại trong toàn bộ mã. Chỉ cần hiển thị một chuỗi Python bằng hàm print().</p>

<p style="text-align: justify;"><strong>Cảnh báo:&nbsp;</strong>nếu bạn muốn hiển thị một chuỗi chứa dấu ngoặc đơn hoặc dấu ngoặc kép, SyntaxError sẽ được trả về.</p>

<p style="text-align: justify;">Python là ngôn ngữ lập trình nhất định bạn cần biết nếu muốn trở thành một chuyên gia trong ngành. Sở dĩ như vậy bởi Python hiện được dùng trong rất nhiều ứng dụng, phần mềm, web và nhiều hơn thế nữa. Thực tế, học Python không khó. Bạn chỉ cần nắm vững các hàm cơ bản và str() là một trong số đó.</p>

<p style="text-align: justify;">Trong&nbsp;Python, hàm&nbsp;<strong>str()</strong>&nbsp;sẽ đưa đối tượng được chọn về dạng chuỗi.</p>

<div style="text-align: justify;">&nbsp;</div>

<h3 style="text-align: justify;">Cú pháp của hàm&nbsp;<strong>str()</strong>&nbsp;trong Python</h3>

<p style="text-align: justify;">Hàm&nbsp;<strong>str()</strong>&nbsp;trong Python có cú pháp là:</p>

<pre id="pre0" style="text-align: justify;">
str(object, encoding=&#039;utf-8&#039;, errors=&#039;strict&#039;)</pre>

<h3 style="text-align: justify;">Tham số của hàm str()</h3>

<p style="text-align: justify;">Hàm&nbsp;<strong>str()</strong>&nbsp;có 3 tham số:</p>

<ul>
	<li style="text-align: justify;"><strong>Đối tượng</strong>: Là đối tượng có thể hiển thị theo dạng chuỗi. Nếu không được cung cấp, kết quả trả về là một chuỗi trống.</li>
	<li style="text-align: justify;"><strong>encoding</strong>: Encoding của một đối tượng. Nếu không được cung cấp, encoding mặc định là UTF-8.</li>
	<li style="text-align: justify;"><strong>errors</strong>: Phản hồi khi encoding bị lỗi. Giá trị mặc định là&nbsp;<strong>&#039;strict&#039;</strong></li>
</ul>

<figure>
<div style="text-align: justify;"><img alt="Hàm str() trong Python trả về dạng chuỗi của một đối tượng" data-adbro-processed="true" data-i="0" data-src="https://st.quantrimang.com/photos/image/2020/06/29/ham-str-trong-python.jpg" data-was-processed="true" height="375" src="https://st.quantrimang.com/photos/image/2020/06/29/ham-str-trong-python.jpg" width="568" /></div>

<figcaption>
<div style="text-align: justify;">Hàm str() trong Python trả về dạng chuỗi của một đối tượng</div>
</figcaption>
</figure>

<h3 style="text-align: justify;">Giá trị trả về của hàm str()</h3>

<p style="text-align: justify;">Hàm&nbsp;<strong>str()</strong>&nbsp;trả về một chuỗi được coi là đại diện không chính thức hoặc có thể in được của một đối tượng.</p>

<h3 style="text-align: justify;">Ví dụ 1: Chuyển đổi đối tượng thành chuỗi bằng str()</h3>

<p style="text-align: justify;">Nếu 2 tham số&nbsp;<strong>encoding</strong>&nbsp;và&nbsp;<strong>errors</strong>&nbsp;không được cung cấp, hàm&nbsp;<strong>str()</strong>&nbsp;gọi method&nbsp;<strong>__str__()</strong>&nbsp;nội bộ của một đối tượng.</p>

<p style="text-align: justify;">Nếu không thể tìm thấy method<strong>&nbsp;__str__()</strong>, nó sẽ gọi hàm&nbsp;<strong>repr(obj)</strong>&nbsp;để thay thế.</p>

<p style="text-align: justify;">Ví dụ:</p>

<pre id="pre1" style="text-align: justify;">
tentrang = str(&#039;Quantrimang.com&#039;)
print(tentrang)</pre>

<p style="text-align: justify;">Khi chạy chương trình, kết quả chúng ta thu được là:</p>

<pre id="pre2" style="text-align: justify;">
Quantrimang.com</pre>

<p style="text-align: justify;">Lưu ý: Biến kết quả sẽ chứa một chuỗi.</p>

<h3 style="text-align: justify;">Ví dụ 2: Hàm str() hoạt động như thế nào với các bytes?</h3>

<p style="text-align: justify;">Nếu tham số&nbsp;<strong>encoding</strong>&nbsp;và&nbsp;<strong>errors</strong>&nbsp;được cung cấp, tham số đầu tiên - đối tượng - sẽ phải là một đối tượng dạng&nbsp;<strong>bytes</strong>&nbsp;(bytes hoặc bytearray).</p>

<p style="text-align: justify;">Nếu đối tượng dạng&nbsp;<strong>bytes</strong>&nbsp;hoặc&nbsp;<strong>bytearray</strong>, hàm&nbsp;<strong>str()</strong>&nbsp;sẽ gọi method&nbsp;<strong>bytes.decode(ecoding, errors)</strong>.</p>

<p style="text-align: justify;">Bên cạnh đó, nó sẽ lấy đối tượng&nbsp;<strong>bytes</strong>&nbsp;trong buffer trước khi gọi&nbsp;<strong>method decode()</strong>.</p>

<div style="text-align: justify;">&nbsp;</div>

<h2 style="text-align: justify;">Lỗi trong chuỗi</h2>

<p style="text-align: justify;">Khi dùng hàm str() trong Python, bạn có thể gặp phải 6 kiểu lỗi sau.</p>

<ul>
	<li style="text-align: justify;">strict (mặc định): Gây lỗi UnicodeDecodeError.</li>
	<li style="text-align: justify;">Ignore: Bỏ qua Unicode chưa được mã hóa.</li>
	<li style="text-align: justify;">Replace: Thay thế unicode chưa được mã hóa bằng dấu chấm hỏi.</li>
	<li style="text-align: justify;">xmlcharrefreplace: Chèn tham chiếu ký tự XML thay cho Unicode không thể mã hóa.</li>
	<li style="text-align: justify;">Namereplace: Chèn chuỗi thoát \N{…} thay cho một Unicode không thể mã hóa.</li>
</ul>

<p style="text-align: justify;">Ví dụ:</p>

<pre id="pre3" style="text-align: justify;">
a = bytes(&quot;ŽString&quot;, encoding = &#039;utf-8&#039;)
s = str(a, encoding = &quot;ascii&quot;, errors =&quot;ignore&quot;)
print(s)</pre>

<p style="text-align: justify;"><strong>Kết quả</strong></p>

<p style="text-align: justify;"><code>String</code></p>

<p style="text-align: justify;">Ở ví dụ trên, ký tự&nbsp;<strong>Ž&nbsp;</strong>sẽ gây lỗi bởi nó không thể được giải mã bằng ASCII. Thế nhưng nó bị bỏ qua bởi các lỗi được thiết lập dưới dạng ignore.</p>

<p style="text-align: justify;">Ví dụ</p>

<pre id="pre4" style="text-align: justify;">
# str() xử lý đối tượng dạng bytes
b = bytes(&#039;Quantrimöng&#039;, encoding=&#039;utf-8&#039;)

print(str(b, encoding=&#039;ascii&#039;, errors=&#039;ignore&#039;))</pre>

<p style="text-align: justify;">Kết quả trả về là:</p>

<pre id="pre5" style="text-align: justify;">
Quantrimng</pre>

<p style="text-align: justify;">Ở đây, ký tự&nbsp;<strong>ö</strong>&nbsp;không thể decode bằng ASCII. Vì thế, nó sẽ gây ra lỗi. Tuy nhiên, chúng ta đã đặt tham số&nbsp;<strong>errors = &#039;ignore&#039;</strong>&nbsp;nên Python sẽ bỏ qua ký tự không thể decode bằng hàm&nbsp;<strong>str()</strong>.</p>

<h2 style="text-align: justify;">Các ngoại lệ của str() trong Python</h2>

<p style="text-align: justify;">Hiện có 6 kiểu lỗi phát sinh từ hàm này:</p>

<ul>
	<li style="text-align: justify;">strict (default): Nó sinh lỗi UnicodeDecodeError.</li>
	<li style="text-align: justify;">Ignore: Nó bỏ qua Unicode unencodable.</li>
	<li style="text-align: justify;">Replace: Nó thay thế Unicode không thể mã hóa bằng dấu hỏi.</li>
	<li style="text-align: justify;">xmlcharrefreplace: Nó chèn tham chiếu ký tự XML thay vì Unicode không thể mã hóa.</li>
	<li style="text-align: justify;">backslashreplace: Chèn một chuỗi \uNNNN Espace thay vì Unicode không thể mã hóa.</li>
	<li style="text-align: justify;">Namereplace: Chèn một chuỗi thoát \N{…} thay vì Unicode không thể mã hóa.</li>
</ul>

<p style="text-align: justify;">Ví dụ:</p>

<pre id="pre6" style="text-align: justify;">
# Python program to demonstrate
# str()

a = bytes(&quot;ŽString&quot;, encoding = &#039;utf-8&#039;)
s = str(a, encoding = &quot;ascii&quot;, errors =&quot;ignore&quot;)
print(s)
</pre>

<p style="text-align: justify;">Kết quả:</p>

<pre id="pre7" style="text-align: justify;">
String</pre>

<p style="text-align: justify;">Ở ví dụ trên, ký tự Z sẽ sinh lỗi vì nó không thể được giải mã bởi ASCII. Thế nhưng nó sẽ bị bỏ qua vì lỗi được đặt dưới dạng&nbsp;<strong>ignore</strong>.</p>
		</div>
				<div id="author">
						<p>
				<strong>Nguồn tin:</strong>
				Quantrimang.com:
			</p>
		</div>
	</div>
	<div id="footer" class="clearfix">
		<div id="url">
			<strong>URL của bản tin này: </strong><a href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/ham-str-trong-python-9856.html" title="Hàm str&#40;&#41; trong Python">https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/ham-str-trong-python-9856.html</a>

		</div>
		<div class="clear"></div>
		<div class="copyright">
			&copy; .&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.
		</div>
		<div id="contact">
			<a href="mailto:admin@nguoicodonvn2008.info">admin@nguoicodonvn2008.info</a>
		</div>
	</div>
</div>
        <div id="timeoutsess" class="chromeframe">
            Bạn đã không sử dụng Site, <a onclick="timeoutsesscancel();" href="https://nguoicodonvn2008.info/#">Bấm vào đây để duy trì trạng thái đăng nhập</a>. Thời gian chờ: <span id="secField"> 60 </span> giây
        </div>
        <div id="openidResult" class="nv-alert" style="display:none"></div>
        <div id="openidBt" data-result="" data-redirect=""></div>
		</script>
		<div class="car-top">
  <span><img src="https://nguoicodonvn2008.info/themes/default/images/car.png" alt=""></span>
</div>
<script src="https://nguoicodonvn2008.info/assets/js/jquery/jquery.min.js"></script>
<script>var nv_base_siteurl="/",nv_lang_data="vi",nv_lang_interface="vi",nv_name_variable="nv",nv_fc_variable="op",nv_lang_variable="language",nv_module_name="news",nv_func_name="savefile",nv_is_user=0, nv_my_ofs=-4,nv_my_abbr="EDT",nv_cookie_prefix="nv4c_e856T",nv_check_pass_mstime=1738000,nv_area_admin=0,nv_safemode=0,theme_responsive=0,nv_recaptcha_ver=2,nv_recaptcha_sitekey="",nv_recaptcha_type="image",XSSsanitize=1;</script>
<script src="https://nguoicodonvn2008.info/assets/js/language/vi.js"></script>
<script src="https://nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js"></script>
<script src="https://nguoicodonvn2008.info/assets/js/global.js"></script>
<script src="https://nguoicodonvn2008.info/assets/js/site.js"></script>
<script src="https://nguoicodonvn2008.info/themes/default/js/news.js"></script>
<script src="https://nguoicodonvn2008.info/themes/default/js/main.js"></script>
<script src="https://nguoicodonvn2008.info/themes/default/js/custom.js"></script>
<script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": "Organization",
            "url": "https://nguoicodonvn2008.info",
            "logo": "https://nguoicodonvn2008.info/uploads/angel.gif"
        }
        </script>
<script src="https://nguoicodonvn2008.info/themes/default/js/bootstrap.min.js"></script>
<script type="text/javascript">
var $scrolltop = $('.car-top');
$scrolltop.on('click', function () {
    $('html,body').animate({
        scrollTop: 0
    }, 800);
    $(this).addClass("car-run");
    setTimeout(function(){ $scrolltop.removeClass('car-run');}, 1000);
    return false;
});
$(window).on('scroll', function ()
{ 
    if($(window).scrollTop() >= 200)
    {
        $scrolltop.addClass("show");
        $scrolltop.addClass("car-down");
    }
    else
    {
       $scrolltop.removeClass("show");
       setTimeout(function(){ $scrolltop.removeClass('car-down');}, 300);
    }
});
</script>
</body>
</html>