Recent Posts

how to use python string and literal.





Hello this is Juny.


python has string data type.
I will look into it in this post.




string


string is the sequence of character.

for example,
"Hello Python" consist of the sequence 'H' 'e' 'l' 'l' 'o' ' ' 'P' 'y' 't' 'h' 'o' 'n'.

python string is immutable data.
it means string cannot be modified.

instead,
python string has various functions to modify string.

they copy the original string.
and then,
they make new string that is modified.




string literal



there are three ways to make a string.


  • double quotes ("string")
  • single quotes ('string')
  • triple quotes ("""string""" or '''string''')

double quotes and single quotes are used for one line string.
triple quotes is used for multiple lines.


let's check it in code.



single = 'hello python'
double = "hello python"
triple1 = '''
hello
python
'''

triple2 = """
hello
python
"""

print(single)
print(double)
print(triple1)
print(triple2)



a string that is made by single quotes is assigned to the variable of "single"
a string that is made by double quotes is assigned to the variable of "double"
strings that is made by triple quotes is assigned to the variable of "triple"



and then,
print out them on screen.






python_string_quotes








how to use unicode in python



if you want to use unicode in python,
'u' or 'U' has to be added at the beginning of string.


and then,
add '\u' to the beginning of unicode.


for example,



unicode = U"\uUNICODE"



how to use quotes in string




quotes is used for delimiter in python string.
error is raised when you try to use quotes in the same quoted string.


but,
there are some ways how to use them.


you can use double quotes in single quoted string.
you can use single quotes in double quoted string.


for example,



single = "hello 'python'"
double = 'hello "python"'

print(single)
print(double)




I used single quotes in the double quoted string.
I used double quotes in the single quoted string.

and then,
I printed out them on the screen.




python_string_quotes_use





length of string



python has built-in function to count length of string.
it is len().




s1 = "hello"
s2 = "hello python\t"
s3 = "hello    python"

print(len(s1))
print(len(s2))
print(len(s3))



"hello" is assigned to s1.
"hello python\t" is assigned to s2.
"hello    python" is assigned to s3.



let's count the lengths of them.




python_string_length




you can check the lengths of them.
and,
'\t' is counted for 1.











how to use python string and literal. how to use python string and literal. Reviewed by Juny on 7월 08, 2019 Rating: 5

댓글 없음:

Powered by Blogger.