Last active
August 29, 2015 14:12
-
-
Save gergob/067556b5fff8f5a5a939 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# string declaration | |
my_str1 = 'simple text' | |
my_str2 = "simple text 2" | |
my_multiline_str = """Hey, this | |
is a multiline | |
string in python""" | |
my_unicode_str = "This is a unicode string containing some special characters like:éáő" | |
print(my_str1) | |
print(my_str2) | |
print(my_multiline_str) | |
print(my_unicode_str) # unicode strings are marked with u"string value" | |
my_p2_unicode_str = u"This a python 2.x unicode string." | |
my_p2_unicode_str2 = unicode("This a python 2.x unicode string.") | |
my_utf8_str = my_p2_unicode_str.encode("utf-8") | |
my_ascii_str = my_p2_unicode_str.encode("ascii") | |
# concatenation and multiplication of strings | |
start_str1 = "The quick brown fox jumps..." | |
start_str2 = "over the lazy dog " | |
concatenated_string = start_str1 + start_str2 | |
print(concatenated_string) # will print The quick brown fox jumps...over the lazy dog | |
list_str = str([1,2,3]) | |
print(list_str) # will print - "[1, 2, 3]" | |
joined_str = "|".join(str(x) for x in [3,2,1]) | |
print(joined_str) # will print - 3|2|1 | |
duplicate_str = start_str1 * 2 + start_str2 * 2 | |
print(duplicate_str) # will print The quick brown fox jumps...The quick brown fox jumps...over the lazy dog over the lazy dog | |
# string searching | |
str1 = "This is a sample string which I will use to showcase search methods of python" | |
print(str1.find("sample")) # will print 10 | |
str1 = str1.replace("e", "3") | |
print(str1) # will print - This is a sampl3 string which I will us3 to showcas3 s3arch m3thods of python | |
# formatting numbers | |
s1 = "{0:d} is a number".format(133) | |
print(s1) # will print - 133 is a number | |
s2 = "{0:f} is a number".format(133.987) | |
print(s2) # will print - 133.987000 is a number | |
s3 = "{0:.2f} is a number".format(133.987) | |
print(s3) # will print - 133.99 is a number --> notice the rounding | |
# format with multiple parameters | |
s4 = "{0} are red, {1} are pink, {2} smell good, but...".format("roses", "violets", "flowers") | |
print(s4) # will print - roses are red, violets are pink, flowers smell good, but... | |
# named parameters and dictionary passing | |
full_name = "John Doe" | |
current_age = 34 | |
s5 = "{name} is {age} years old.".format(name=full_name, age=current_age) | |
print(s5) # will print - John Doe is 34 years old. | |
vals = { "first_name" : "John", "last_name" : "Doe", "age":33 } | |
s6 = "{first_name} {last_name} is {age} years old.".format(**vals) | |
print(s6) # will print - John Doe is 33 years old. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment