# -------------------------------------------------------------
# Substituting part of a string by another string using
# replace method


# Example: Sometimes you want to replace or manipulate
# separators between items in the string

s = "neon, lead,tin, carbon, iron,tin,gold, lead,zinc, molybdenum"
# note irregular spaces after the commas

# Replace commas by semicolons
s2 = s.replace( ",", ";" )
print( s2 )
print()

# Add spaces, so that each semicolon is followed by one space
# It takes a little trick
#    1. Add space after *each* semicolon
#       == replace semicolon by semicolon + space
s3 = s2.replace( ";", "; " )
print( s3 )
print()
#    2. substitute each double space by single space
s3 = s3.replace( "  ", " " )
print( s3 )
print()


# CAUTION: replace is NOT all-powerful,
# it neglects overlapping identical copies of substrings.

s = "abababab"
s2 = s.replace("abab", "bcde")
print( s )
print( s2 )

# Note that there are THREE subtrings abab in abababab.
# Only two were replaced.



# -------------------------------------------------------------
# Counting occurences

s = "Hello world!"
print( s.count("o"), s.count("or") )

# CAUTION: count is NOT all-powerful,
# it neglects overlapping identical copies of substrings.

s = "BEWARE! count 'a' and 'aa' in 'aaaaa'"
print( s.count("a"), s.count("aa"), s.count("aaa") )


# -------------------------------------------------------------
# String splitting
# Any character may used a separator

s = "a bc, def ghij, klmno pqrs, tuv wx, y"
split1 = s.split(" ")
split2 = s.split(",")
print( s )
print( split1 )
print( split2 )


# -------------------------------------------------------------
# Example of more special function join()
# It glues together all elements of a list
# using another specified string as a "glue":


statement = "Some cities are: "
cities = ["Prague", "Madrid", "Athens", "Stockholm"]
print( cities )
joined = " and ".join(cities)
print( statement + joined + "." )
joined = ", ".join(cities)
print( statement + joined + "." )
joined = " xyz ".join(cities)
print( statement + joined + "." )




