lenguaje = "Python" # estilo viejo a = "%s feliz" % lenguaje print(a) # nuevo estilo a = "{} feliz".format(lenguaje) print(a) # python 3.6+ a = f"{lenguaje} feliz" print(a) def language_rocks(language): return language + " rocks!" print(language_rocks("Python")) def language_info(language, users_estimate): return ( language + " rocks! Did you know that " + language + " has around " + str(users_estimate) + " users?!" ) print(language_info("Python", 10)) name, age = "John", 73 print("%(name)s is %(age)d years old." % {"name": name, "age": age}) print("{name} is {age} years old.".format(name=name, age=age)) print(f"{name} is {age} years old.") data = {"name": "John", "age": 73} print("%(name)s is %(age)d years old." % data) print("{data[name]} is {data[age]} years old.".format(data=data)) print("{name} is {age} years old.".format(**data)) print(f"{data['name']} is {data['age']} years old.") class ConvolutedExample: values = [{"name": "Charles"}, {42: "William"}] ce = ConvolutedExample() print("Name is: {ce.values[0][name]}".format(ce=ce)) print(f"Name is: {ce.values[0]['name']}") data = [("Toyota", "Japanese"), ("Ford", "USA")] for brand, country in data: print(f"{brand:>7}, {country:>9}") data = [("Toyota", "Japanese"), ("Ford", "USA"), ("Lamborghini", "Italy")] for brand, country in data: print(f"{brand:>7}, {country:>9}") data = [("Toyota", "Japanese"), ("Ford", "USA"), ("Lamborghini", "Italy")] # Compute brand width and country width needed for formatting. bw = 1 + max(len(brand) for brand, _ in data) cw = 1 + max(len(country) for _, country in data) for brand, country in data: print(f"{brand:>{bw}}, {country:>{cw}}") month = "November" prec = 3 value = 2.7182 print("%.*s = %.*f" % (prec, month, prec, value)) print("{:.{prec}} = {:.{prec}f}".format(month, value, prec=prec)) print(f"{month:.{prec}} = {value:.{prec}f}") class YN: def __format__(self, format_spec): return "N" if "n" in format_spec else "Y" print("{:aaabbbccc}".format(YN())) # Result is 'Y' print(f"{YN():nope}") # Result is 'N' # Some random variables: name, age, w = "John", 73, 10 # ✅ Prefer... print(f"{name!s} {name!r}") print(f"{name:<10}") print(f"{name} is {age} years old.") print(f"{name:^{w}}") def get_greeting(language): if language == "pt": return "Olá, {}!" else: return "Hello, {}!" lang = input(" [en/pt] >> ") name = input(" your name >> ") print(get_greeting(lang).format(name)) # Using C-style string formatting: def language_info_cstyle(language, users_estimate): return "%s rocks! Did you know that %s has around %d users?!" % ( language, language, users_estimate, ) # Using the Python 3 `.format` method from strings: def language_info_format(language, users_estimate): return "{} rocks! Did you know that {} has around {} users?!".format( language, language, users_estimate ) # Using f-strings, from Python 3.6+: def language_info_fstring(language, users_estimate): return ( f"{language} rocks! Did you know that {language}" + f" has around {users_estimate} users?!" )