We provide effective and economically affordable training courses for R and Python, click here for more details and course registration !

String variables in Python are data objects encapsulated in double or single quotes. For example we can create a string variable ‘msg’ and print it out in the following code.

#create a string variable
msg = "I am from USA"
print(msg)
#output
I am from USA

#string variable can be created using single quotes too
msg2 = 'I promist to finish job tonight'
print(msg2)
#output
I promist to finish job tonight

The basic function working on strings are print string with upper case, lower case, or title form.

myname = "wilson zhang"
#upper case
print(myname.upper())
#output
WILSON ZHANG

#lower case
print(myname.lower())
#output
wilson zhang

#title form
print(myname.title())
#output
Wilson Zhang

Several strings can be concatenated using plus symbol.

f_name = "Wilson"
l_name = "Zhang"
full_name = f_name + " " + l_name
print(full_name)
#output
Wilson Zhang

msg3 = "Good morning, " + full_name.title() + "!"
print(msg3)
#output
Good morning, Wilson Zhang!

Strings can also be combined with new line and tab spaces.

#combined with new line 
print("Countries:\nUSA\nJapan\nNorway")
#output
Countries:
USA
Japan
Norway

#combined with new line and tab
print("Languages:\n\tUSA\n\tJapan\n\tNorway")
#output
Languages:
	USA
	Japan

The white spaces with strings can be removed from left side of the string, from the right side or on both sides of the string.

favorite_food = ' pizza '
#remove white space from left side of the string
favorite_food.lstrip()
Out[11]: 'pizza '

#remove white space from right side of the string
favorite_food.rstrip()
Out[12]: ' pizza'

remove white space from both sides of the string
favorite_food.strip()
Out[13]: 'pizza'

For more tutorials of learning Python, you can watch Python full video in 10 hours from our YouTube channel !


0 Comments

Leave a Reply

Avatar placeholder