Hive-blogger avatar

Python Rules Of Coding: String literals

alrashel

Published: 05 May 2020 › Updated: 05 May 2020Python Rules Of Coding: String literals

Python Rules Of Coding: String literals

Previous
Python Rules Of Coding: Comments

code-1084923_1280.png

Source

Python Rules Of Coding: String literals

print(" Hello, World! ")

In the above code, the string literal is "Hello, World!" with quotation marks and the string value is Hello, World! without quotation marks. In short, the string value is the output from a string literal code. Therefore we understand that string literals and string values are not the same.

Sometimes we need quoting a source code in string values. For this why we have to add additional formatting to string literals so that we get our expected string values as output.

Quotes

We can use double quotes to enclose a string literals if we want to embed single quotes within a string value

"He says, 'Hello dear!' "

Output the string value:

He says, 'Hello dear!'

Same way, use single quotes to enclose the string literals and embed double quotes within the string value.

'He says, "Hello dear!" '

Output the string value:

He says, "Hello dear!"

Multiple Lines

Sometimes it needs to print strings on multiple lines with grouped, orderly and formatted as a poem, lyrics, letter.

In this case, we can use triple double quotes (" " ") or triple single quotes (' ' ')

" " "
Multiple lines
string literals.
Enclosed by triple double-quotes. 
" " "

'''
Multiple lines
string literals.
Enclosed by triple single-quotes. 
'''

Escape Characters

To format the string literals in a specific way we can use
Escape character. Along with another character, Escape character begins with the backslash ( \ ) .

Here is a list of some escape characters from w3schools:

escape1.JPG

 str = 'It\'s OK.'
  print(str)

Output:

It's OK.

str = "Embed backslash \\ in string value."
 print(str) 

Output:

Embed backslash \ in string value.

We can also remove whitespace by using the backslash ( \ ) escape character. Learn more

There is another kind of string value called Raw strings. Formatted string literals can be outputted as a string value by using an escape character ' r ' in front of a string literals.

print(r"Rony says,\"The balloon\'s color is black.\"")

Output

Rony says,"The balloon's color is black."

Next
Python Rules Of Coding: User Documentations

----------------------------------------------------------------------

Leave Python Rules Of Coding: String literals to:

Written by

Passionate software developer and interests in Travelling, Blogging, Photography and active lifestyle.

Read more #stem posts


Best Posts From Hive-blogger

We have not curated any of alrashel's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Hive-blogger