SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы

Назад

Strings


Метки: python

The above example also shows a little bit about Python string handling, which is the best of any language I’ve seen. You can use single or double quotes to represent strings, which is very nice because if you surround a string with double quotes, you can embed single quotes and vice versa:

# PythonForProgrammers/strings.py
print("That isn't a horse")
print('You are not a "Viking"')
print("""You're just pounding two
coconut halves together.""")
print('''"Oh no!" He exclaimed.
"It's the blemange!"''')
print(r'c:\python\lib\utils')

Note that Python was not named after the snake, but rather the Monty Python comedy troupe, and so examples are virtually required to include Python-esque references.

The triple-quote syntax quotes everything, including newlines. This makes it particularly useful for doing things like generating web pages (Python is an especially good CGI language), since you can just triple-quote the entire page that you want without any other editing.

The ‘r‘ right before a string means “raw,” which takes the backslashes literally so you don’t have to put in an extra backslash in order to insert a literal backslash.

Substitution in strings is exceptionally easy, since Python uses C’s printf() substitution syntax, but for any string at all. You simply follow the string with a ‘%‘ and the values to substitute:

# PythonForProgrammers/stringFormatting.py
val = 47
print("The number is %d" % val)
val2 = 63.4
s = "val: %d, val2: %f" % (val, val2)
print(s)

As you can see in the second case, if you have more than one argument you surround them in parentheses (this forms a tuple, which is a list that cannot be modified - you can also use regular lists for multiple arguments, but tuples are typical).

All the formatting from printf() is available, including control over the number of decimal places and alignment. Python also has very sophisticated regular expressions.