Recent Posts

python string operators




Hello I am Juny.

we will study how to use string operator in python.



string operator



string has operation.
in general,
there are logical, arithmetic operations.
string cannot use all the operations.

we will study which one can be used for string.





assign operation



we can assign string literal to variable with assign operation.



str1 = "abcd"
str2 = str1

print(str1)
print(str2)




"abcd" is assigned to str1 with assign operation "="
instead of literal,
variable can be also assigned to another variable.





python string operator assign


compare operation


we can compare if or not strings are same.



  • if or not a string is equal to another string. "=="
  • if or not a string is not equal to another string. "!="




str1 = "abcd"
str2 = str1
str3 = "aacd"

print(str1 == str2)
print(str1 != str2)
print(str1 == str3)
print(str3 != "aacd")




we use "==" to compare if or not they are equal.
the contrary,
we use "!=" to compare if or not they are not equal.


if they are equal, it return "true"
otherwise,
return "false"




python string operator compare



"str1 == str2" will return "true".

in second, 
str1 is equal to str2. so it will return "false".

in third, 
"abcd" is not equal to "aacd". so, it will return "false".

in last,
str3 is equal to "aacd". so it will return "false"


variable can be compared with literal.



add operation



it is "+"
it can concatenate each string.

let's check it in code.



str1 = 'aaa'
str2 = 'bbb'
str3 = 'ccc'
str4 = str1 + str2 + str3
str5 = 'aaa' 'bbb' 'ccc'

print(str4)
print(str5)
print(str1,str2,str3)




str1, str2 and str3 are concatenated by "+".
and then, the result is assigned to str4.
three strings are aligned in sequence.
then, the result is assigned to str5.

lastly,
three string are passed to print function.





python string operator plus



"aaabbbccc" is printed out as the result of str4.
it is same as the output of str5.


the print function that has three string parameter printed out "aaa bbb ccc".
it has spaces among strings.

there are more ways to concatenate strings in python.
we will study them in the part of string functions.



multiply operator


it is "*"
if we use it,
string will repeat.



let's check it in code.


str1 = "aa" * 5

print(str1)




"aa" is multiplied by 5.
in the output,
"aa" is repeat for 5 times.




python string operator multiply







python string operators python string operators Reviewed by Juny on 7월 11, 2019 Rating: 5

댓글 없음:

Powered by Blogger.