برخی اوقات ممکن است بخواهید یک عبارت را در چند خط بنویسید، اما نوشتن عبارت و رشته بین دو '' یا "" نمیتواند بیش از یک خط را شامل شود.
مثال زیر را در نظر بگیرید:
و خروجی آن نیز به این صورت می باشد:
در واقع متغیر string حاوی یک عبارت می باشد که در چند خط نوشتیم تا کد ما خوانایی بیشتری داشته باشد. دقت کنید که این جا مد نظر ما خود کد میباشد و کاری به خروجی نداریم.
برای این که این موضوع بهتر روشن شود متغیرها را به این شکل در نظر بگیرید:
Python
string1 = 'hi everyone, this the first line of a long string provided for pythonlearner.ir to see how messy it is! so let us continue it more to see it better.'
string2 = 'hi everyone, it is the first line of a long string, but it breaks' \
' into the other line so that it increases the readability to see' \
' the difference between variables string1 and string2'
print(string1)
print(string2)
خروجی:
Code
hi everyone, this the first line of a long string provided for pythonlearner.ir to see how messy it is! so let us continue it more to see it better.
hi everyone, it is the first line of a long string, but it breaks into the other line so that it increases the readability to see the difference between variables string1 and string2
اما برای این که بتوانیم متغیر string2 را به همین فرمت و در چند لاین بنویسیم باید راه دیگری را در پیش گیریم.
در پایتون برای این کار از سه علامت ' یا " برای این کار استفاده می کنیم.
متغیر string2 را در نظر بگیرید:
Python
string2 = '''hi everyone, it is the first line of a long string, but it breaks
into the other line so that it increases the readability to see the difference
between variables string1 and string2'''
print(f'this is string2 with triple \'\'\': {string2} \n')
string2 = """hi everyone, it is the first line of a long string, but it breaks
into the other line so that it increases the readability to see
the difference between variables string1 and string2"""
print(f'this is string2 with triple """: {string2}')
خروجی:
Code
this is string2 with triple ''': hi everyone, it is the first line of a long string, but it breaks
into the other line so that it increases the readability to see the difference
between variables string1 and string2
this is string2 with triple """: hi everyone, it is the first line of a long string, but it breaks
into the other line so that it increases the readability to see
the difference between variables string1 and string2
همان طور که میبینید، عبارت چند خطی ما دقیقا به همان شکلی خروجی میدهد که در کد پایتون نوشتیم.