标签归档:string

如何在python中写字符串文字而不必转义它们?

问题:如何在python中写字符串文字而不必转义它们?

有没有一种方法可以在python中声明字符串变量,以使其中的所有内容都自动转义,或者具有其原义字符值?

不是问如何用斜杠将引号转义,这是显而易见的。我要的是一种通用的方式,使所有内容都以字符串文字形式显示,这样我就不必手动检查并转义非常大的字符串的所有内容。有人知道解决方案吗?谢谢!

Is there a way to declare a string variable in python such that everything inside of it is automatically escaped, or has its literal character value?

I’m not asking how to escape the quotes with slashes, that’s obvious. What I’m asking for is a general purpose way for making everything in a string literal so that I don’t have to manually go through and escape everything for very large strings. Anyone know of a solution? Thanks!


回答 0

原始字符串文字:

>>> r'abc\dev\t'
'abc\\dev\\t'

Raw string literals:

>>> r'abc\dev\t'
'abc\\dev\\t'

回答 1

如果要处理非常大的字符串,特别是多行字符串,请注意三引号语法:

a = r"""This is a multiline string
with more than one line
in the source code."""

If you’re dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:

a = r"""This is a multiline string
with more than one line
in the source code."""

回答 2

哪有这回事。看起来您想要在Perl和shell中提供“此处文档”之类的东西,但是Python没有。

仅使用原始字符串或多行字符串意味着不必担心太多事情。如果您使用原始字符串,则仍然必须在终端“ \”周围解决,并且使用任何字符串解决方案,都必须担心如果数据中包含了结束符“,’,’,’或”“” 。

也就是说,无法获取字符串

 '   ''' """  " \

正确存储在任何Python字符串文字中,而无需进行某种内部转义。

There is no such thing. It looks like you want something like “here documents” in Perl and the shells, but Python doesn’t have that.

Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal “\” and with any string solution you’ll have to worry about the closing “, ‘, ”’ or “”” if it is included in your data.

That is, there’s no way to have the string

 '   ''' """  " \

properly stored in any Python string literal without internal escaping of some sort.


回答 3

您可以在这里找到Python的字符串文字文档:

http://docs.python.org/tutorial/introduction.html#strings

和这里:

http://docs.python.org/reference/lexical_analysis.html#literals

最简单的示例将使用’r’前缀:

ss = r'Hello\nWorld'
print(ss)
Hello\nWorld

You will find Python’s string literal documentation here:

http://docs.python.org/tutorial/introduction.html#strings

and here:

http://docs.python.org/reference/lexical_analysis.html#literals

The simplest example would be using the ‘r’ prefix:

ss = r'Hello\nWorld'
print(ss)
Hello\nWorld

回答 4

(假设您不需要直接在Python代码中输入字符串)

为了解决安德鲁·达尔克(Andrew Dalke)指出的问题,只需在文本文件中键入文字字符串,然后使用它即可;

input_ = '/directory_of_text_file/your_text_file.txt' 
input_open   = open(input_,'r+')
input_string = input_open.read()

print input_string

这将打印文本文件中任何内容的文字文本,即使它是;

 '   ''' """   \

虽然不是很有趣,也不是最佳选择,但它很有用,尤其是当您有3页需要转义字符的代码时。

(Assuming you are not required to input the string from directly within Python code)

to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;

input_ = '/directory_of_text_file/your_text_file.txt' 
input_open   = open(input_,'r+')
input_string = input_open.read()

print input_string

This will print the literal text of whatever is in the text file, even if it is;

 '   ''' """  “ \

Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.


回答 5

如果string是变量,请使用。repr方法就可以了:

>>> s = '\tgherkin\n'

>>> s
'\tgherkin\n'

>>> print(s)
    gherkin

>>> print(s.__repr__())
'\tgherkin\n'

if string is a variable, use the .repr method on it:

>>> s = '\tgherkin\n'

>>> s
'\tgherkin\n'

>>> print(s)
    gherkin

>>> print(s.__repr__())
'\tgherkin\n'

替换文件内容中的字符串

问题:替换文件内容中的字符串

如何打开文件Stud.txt,然后用“橙色”替换出现的“ A”?

How can I open a file, Stud.txt, and then replace any occurences of “A” with “Orange”?


回答 0

with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))
with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))

回答 1

如果要替换同一文件中的字符串,则可能必须将其内容读入局部变量,将其关闭,然后重新打开以进行写入:

在此示例中,我使用with语句,该语句with块终止后关闭文件-通常在最后一条命令完成执行时执行,或在exceptions情况下执行。

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

值得一提的是,如果文件名不同,我们可以用一条with语句来做得更好。

If you’d like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:

I am using the with statement in this example, which closes the file after the with block is terminated – either normally when the last command finishes executing, or by an exception.

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.


回答 2

#!/usr/bin/python

with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

with open(FileName, "w") as f:
    f.write(newText)
#!/usr/bin/python

with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

with open(FileName, "w") as f:
    f.write(newText)

回答 3

就像是

file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

Something like

file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

回答 4

with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)
with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)

回答 5

如果您使用的是Linux,并且只想替换单词dog,则cat可以执行以下操作:

text.txt:

Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!

Linux命令:

sed -i 's/dog/cat/g' test.txt

输出:

Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!

原始帖子:https : //askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands

If you are on linux and just want to replace the word dog with catyou can do:

text.txt:

Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!

Linux Command:

sed -i 's/dog/cat/g' test.txt

Output:

Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!

Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands


回答 6

使用pathlib(https://docs.python.org/3/library/pathlib.html

from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))

如果输入文件和输出文件不同,则将对read_text和使用两个不同的变量write_text

如果您希望更改比单个替换更复杂,则可以将结果分配read_text给一个变量,对其进行处理,然后将新内容保存到另一个变量,然后使用保存新内容write_text

如果您的文件很大,则最好不要读取内存中的整个文件,而应像Gareth Davidson在另一个答案中显示的那样逐行处理(https://stackoverflow.com/a/4128192/3981273) ,当然需要使用两个不同的文件进行输入和输出。

Using pathlib (https://docs.python.org/3/library/pathlib.html)

from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))

If input and output files were different you would use two different variables for read_text and write_text.

If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.

If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.


回答 7

最简单的方法是使用正则表达式进行此操作,假设您要遍历文件中的每一行(存储“ A”的位置),则可以…

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
    input.write(each)

easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where ‘A’ would be stored) you do…

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
    input.write(each)

Python:获取列表中第一个字符串的第一个字符?

问题:Python:获取列表中第一个字符串的第一个字符?

如何从Python列表中的第一个字符串中获取第一个字符?

看来我可以使用,mylist[0][1:]但不能给我第一个字符。

>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'

How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the first character.

>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'

回答 0

你几乎是对的。最简单的方法是

mylist[0][0]   # get the first character from the first item in the list

mylist[0][:1]  # get up to the first character in the first item in the list

也可以。

你想结束的第一个字符(字符零)后,未启动的第一个字符(字符零),这是以后有什么在你的问题的手段的代码。

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.


回答 1

获取裸python字符串的第一个字符:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

从python列表的第一个位置的字符串中获取第一个字符:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

许多人在这里绊倒了,因为他们混淆了Python列表对象的运算符和Numpy ndarray对象的运算符:

Numpy操作与python列表操作非常不同。

绕过Python的“列表切片,索引,子集”和Numpy的“掩码,切片,子集,索引,然后是numpy的增强式花式索引”这两个相互冲突的世界。

这两个视频为我清除了一切:

PyCon 2015撰写的“使用NumPy消除循环,快速进行数值计算”:https ://youtu.be/EEUXKG97YRw ? t = 22m22s

Alexandre Chabot LeClerc撰写的“ NumPy初学者| SciPy 2016教程”:https ://youtu.be/gtejJ3RCddE ? t = 1h24m54s

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python’s “list slicing, indexing, subsetting” and then Numpy’s “masking, slicing, subsetting, indexing, then numpy’s enhanced fancy indexing”.

These two videos cleared things up for me:

“Losing your Loops, Fast Numerical Computing with NumPy” by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

“NumPy Beginner | SciPy 2016 Tutorial” by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s


回答 2

从0开始在python中建立索引。您编写了[1:]在任何情况下都不会返回第一个字符-这将为您返回其余的字符串(第一个字符除外)。

如果具有以下结构:

mylist = ['base', 'sample', 'test']

并希望为第一个字符串(项目)获取拳头字符:

myList[0][0]
>>> b

如果所有第一个字符:

[x[0] for x in myList]
>>> ['b', 's', 't']    

如果您有文字:

text = 'base sample test'
text.split()[0][0]
>>> b

Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case – this will return you a rest(except first char) of string.

If you have the following structure:

mylist = ['base', 'sample', 'test']

And want to get fist char for the first one string(item):

myList[0][0]
>>> b

If all first chars:

[x[0] for x in myList]
>>> ['b', 's', 't']    

If you have a text:

text = 'base sample test'
text.split()[0][0]
>>> b

回答 3

尝试mylist[0][0]。这应该返回第一个字符。

Try mylist[0][0]. This should return the first character.


如何“正确”打印列表?

问题:如何“正确”打印列表?

所以我有一个清单:

['x', 3, 'b']

我希望输出为:

[x, 3, b]

如何在python中执行此操作?

如果我这样做str(['x', 3, 'b']),我会用引号引起来,但我不希望引号。

So I have a list:

['x', 3, 'b']

And I want the output to be:

[x, 3, b]

How can I do this in python?

If I do str(['x', 3, 'b']), I get one with quotes, but I don’t want quotes.


回答 0

在Python 2中:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

在Python 3中(其中print是内置函数,而不再是语法功能):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

两者都返回:

[x, 3, b]

这是使用map()函数调用mylist的每个元素的str ,创建一个新的字符串列表,然后用str.join()。然后,%字符串格式运算符将字符串替换为%sin ,而不是in "[%s]"

In Python 2:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

In Python 3 (where print is a builtin function and not a syntax feature anymore):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

Both return:

[x, 3, b]

This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".


回答 1

这是简单的代码,因此,如果您是新手,则应该足够容易地理解它。

    mylist = ["x", 3, "b"]
    for items in mylist:
        print(items)

如您所愿,它会全部打印不带引号的内容。

This is simple code, so if you are new you should understand it easily enough.

    mylist = ["x", 3, "b"]
    for items in mylist:
        print(items)

It prints all of them without quotes, like you wanted.


回答 2

仅使用打印:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

回答 3

如果您使用的是Python3:

print('[',end='');print(*L, sep=', ', end='');print(']')

If you are using Python3:

print('[',end='');print(*L, sep=', ', end='');print(']')

回答 4

map建议不要使用join可以接受迭代器的生成器表达式:

def get_nice_string(list_or_iterator):
    return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"

这里join是字符串类的成员函数str。它使用一个参数:一个字符串列表(或迭代器),然后返回一个新字符串,其中所有元素都由串联,

Instead of using map, I’d recommend using a generator expression with the capability of join to accept an iterator:

def get_nice_string(list_or_iterator):
    return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"

Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.


回答 5

您可以使用它的字符串中删除所有不想要的字符translate()的方法Nonetable参数,随后包含字符(S)你想为它取出一个字符串deletechars参数。

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

如果您使用的是2.6之前的Python版本,则需要使用string模块的translate()功能,因为直到2.6才添加了None作为table参数传递的功能。使用它看起来像这样:

import string

print string.translate(str(lst), None, "'")

使用此string.translate()功能在2.6+中也可以使用,因此使用它可能是更可取的。

You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

If you’re using a version of Python before 2.6, you’ll need to use the string module’s translate() function instead because the ability to pass None as the table argument wasn’t added until Python 2.6. Using it looks like this:

import string

print string.translate(str(lst), None, "'")

Using the string.translate() function will also work in 2.6+, so using it might be preferable.


回答 6

这是一个交互式会话,显示了@TokenMacGuy的一线代码中的一些步骤。首先,他使用该map函数将列表中的每个项目转换为字符串(实际上,他正在创建一个新列表,而不是在旧列表中进行转换)。然后,他使用string方法join将这些字符串结合', '在一起。其余的只是字符串格式,这非常简单。(编辑:此实例非常简单;字符串格式通常会有些复杂。)

请注意,使用join是从几个子字符串构建字符串的一种简单而有效的方法,比通过向字符串中连续添加字符串(这样做涉及在幕后进行大量复制)来实现效率要高得多。

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

Here’s an interactive session showing some of the steps in @TokenMacGuy’s one-liner. First he uses the map function to convert each item in the list to a string (actually, he’s making a new list, not converting the items in the old list). Then he’s using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

回答 7

使用.format字符串格式化,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

输出:

[x, 3, b]

说明:

  1. map用于将列表的每个元素映射到string类型。
  2. 这些元素通过,分隔符连接在一起成为一个字符串。
  3. 我们在打印语句中使用[]来显示列表大括号。

参考: .format有关字符串格式PEP-3101

Using .format for string formatting,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

Output:

[x, 3, b]

Explanation:

  1. map is used to map each element of the list to string type.
  2. The elements are joined together into a string with , as separator.
  3. We use [ and ] in the print statement to show the list braces.

Reference: .format for string formatting PEP-3101


回答 8

@AniMenon启发我编写了一个pythonic更通用的解决方案。

mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))

它仅使用该format方法。没有任何痕迹str,并且允许对元素格式进行微调。例如,如果将浮点数作为列表的元素,则在这种情况下,可以通过添加转化说明符来调整其格式:.2f

mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))

输出是相当不错的:

[1.85, -6.33, 4000.21]

I was inspired by @AniMenon to write a pythonic more general solution.

mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))

It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format. For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f

mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))

The output is quite decent:

[1.85, -6.33, 4000.21]

如何删除字符串中的前导和尾随零?Python

问题:如何删除字符串中的前导和尾随零?Python

我有几个像这样的字母数字字符串

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']

除去尾随零的理想输出为:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']

前导尾随零的期望输出为:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']

除去前导零和尾随零的期望输出为:

listOfNum = ['231512-n','1209123100000-n', 'alphanumeric', 'alphanumeric']

目前,我已经按照以下方式进行操作,如果有的话,请提出一种更好的方法:

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \
'000alphanumeric']
trailingremoved = []
leadingremoved = []
bothremoved = []

# Remove trailing
for i in listOfNum:
  while i[-1] == "0":
    i = i[:-1]
  trailingremoved.append(i)

# Remove leading
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  leadingremoved.append(i)

# Remove both
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  while i[-1] == "0":
    i = i[:-1]
  bothremoved.append(i)

I have several alphanumeric strings like these

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']

The desired output for removing trailing zeros would be:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']

The desired output for leading trailing zeros would be:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']

The desire output for removing both leading and trailing zeros would be:

listOfNum = ['231512-n','1209123100000-n', 'alphanumeric', 'alphanumeric']

For now i’ve been doing it the following way, please suggest a better way if there is:

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \
'000alphanumeric']
trailingremoved = []
leadingremoved = []
bothremoved = []

# Remove trailing
for i in listOfNum:
  while i[-1] == "0":
    i = i[:-1]
  trailingremoved.append(i)

# Remove leading
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  leadingremoved.append(i)

# Remove both
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  while i[-1] == "0":
    i = i[:-1]
  bothremoved.append(i)

回答 0

那基本的

your_string.strip("0")

删除尾随和前导零?如果您只想删除尾随零,请.rstrip改用(.lstrip仅用于前导零)。

[ 文档中的更多信息。]

您可以使用一些列表推导来获得所需的序列,如下所示:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

What about a basic

your_string.strip("0")

to remove both trailing and leading zeros ? If you’re only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

[More info in the doc.]

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

回答 1

删除前导+尾随的“ 0”:

list = [i.strip('0') for i in listOfNum ]

删除前导“ 0”:

list = [ i.lstrip('0') for i in listOfNum ]

删除尾随的“ 0”:

list = [ i.rstrip('0') for i in listOfNum ]

Remove leading + trailing ‘0’:

list = [i.strip('0') for i in listOfNum ]

Remove leading ‘0’:

list = [ i.lstrip('0') for i in listOfNum ]

Remove trailing ‘0’:

list = [ i.rstrip('0') for i in listOfNum ]

回答 2

您可以简单地通过bool做到这一点:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

回答 3

您是否尝试了strip()

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']

Did you try with strip() :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']

回答 4

str.strip是解决这种情况的最佳方法,但more_itertools.strip还是一种通用解决方案,可从迭代中剥离前导元素和尾随元素:

import more_itertools as mit


iterables = ["231512-n\n","  12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']

细节

注意,这里我们"0"将满足谓词的其他元素中的前导和尾随s 剥离。此工具不仅限于字符串。

另请参阅docs,以获取更多的示例

more_itertools是可通过安装的第三方库> pip install more_itertools

str.strip is the best approach for this situation, but more_itertools.strip is also a general solution that strips both leading and trailing elements from an iterable:

Code

import more_itertools as mit


iterables = ["231512-n\n","  12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']

Details

Notice, here we strip both leading and trailing "0"s among other elements that satisfy a predicate. This tool is not limited to strings.

See also docs for more examples of

more_itertools is a third-party library installable via > pip install more_itertools.


回答 5

假设列表中还有其他数据类型(不仅是字符串),请尝试此操作。这将从字符串中删除尾随和前导零,并使其他数据类型保持不变。这也处理特殊情况s =’0′

例如

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']

Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = ‘0’

e.g

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']


为什么带有f字符串的f'{{{74}}}’与f'{{74}}’相同?

问题:为什么带有f字符串的f'{{{74}}}’与f'{{74}}’相同?

f字符串可从Python 3.6中获得,对于格式化字符串非常有用:

>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'

Python 3的f字符串中阅读有关它们的更多信息:改进的字符串格式语法(指南)。我发现了一个有趣的模式:

请注意,使用三重花括号将导致字符串中只有一个大括号:

>>> f"{{{74}}}"
'{74}'

但是,如果使用的括号多于三个,则可以显示更多的括号:

>>> f"{{{{74}}}}"
'{{74}}'

确实是这样:

>>> f'{74}'
'74'

>>> f'{{74}}'
'{74}'

现在,如果我们从两个传递{到三个,结果将是相同的:

>>> f'{{{74}}}'
'{74}'           # same as f'{{74}}' !

因此,我们最多需要4个!({{{{)获得两个大括号作为输出:

>>> f'{{{{74}}}}'
'{{74}}'

为什么是这样?从那时起,用两个花括号使Python需要一个额外的花括号会发生什么?

f-Strings are available from Python 3.6 and are very useful for formatting strings:

>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'

Reading more about them in Python 3’s f-Strings: An Improved String Formatting Syntax (Guide). I found an interesting pattern:

Note that using triple braces will result in there being only single braces in your string:

>>> f"{{{74}}}"
'{74}'

However, you can get more braces to show if you use more than triple braces:

>>> f"{{{{74}}}}"
'{{74}}'

And this is exactly the case:

>>> f'{74}'
'74'

>>> f'{{74}}'
'{74}'

Now if we pass from two { to three, the result is the same:

>>> f'{{{74}}}'
'{74}'           # same as f'{{74}}' !

So we need up to 4! ({{{{) to get two braces as an output:

>>> f'{{{{74}}}}'
'{{74}}'

Why is this? What happens with two braces to have Python require an extra one from that moment on?


回答 0

双括号逃脱牙套,所以没有发生插值:{{{}}}。并74保持不变的字符串,'74'

与三括号相同,外部的双括号被转义。另一方面,内部括号导致值的常规字符串插值74

也就是说,该字符串f'{{{74}}}'等效于f'{{ {74} }}',但没有空格(或等效于'{' + f'{74}' + '}')。

在用变量替换数字常量时,您可以看到区别:

In [1]: x = 74

In [2]: f'{{x}}'
Out[2]: '{x}'

In [3]: f'{{{x}}}'
Out[3]: '{74}'

Double braces escape the braces, so that no interpolation happens: {{{, and }}}. And 74 remains an unchanged string, '74'.

With triple braces, the outer double braces are escaped, same as above. The inner braces, on the other hand, lead to regular string interpolation of the value 74.

That is, the string f'{{{74}}}' is equivalent to f'{{ {74} }}', but without spaces (or, equivalently, to '{' + f'{74}' + '}').

You can see the difference when replacing the numeric constant by a variable:

In [1]: x = 74

In [2]: f'{{x}}'
Out[2]: '{x}'

In [3]: f'{{{x}}}'
Out[3]: '{74}'

Python:如何打印范围az?

问题:Python:如何打印范围az?

1.打印: abcdefghijklmn

2.每秒: acegikm

3.将url索引附加到{ hello.com/、hej.com/、…、hallo.com/}:hello.com/a hej.com/b … hallo.com/n

1. Print a-n: a b c d e f g h i j k l m n

2. Every second in a-n: a c e g i k m

3. Append a-n to index of urls{hello.com/, hej.com/, …, hallo.com/}: hello.com/a hej.com/b … hallo.com/n


回答 0

>>> import string
>>> string.ascii_lowercase[:14]
'abcdefghijklmn'
>>> string.ascii_lowercase[:14:2]
'acegikm'

要执行网址,您可以使用类似以下内容的网址

[i + j for i, j in zip(list_of_urls, string.ascii_lowercase[:14])]
>>> import string
>>> string.ascii_lowercase[:14]
'abcdefghijklmn'
>>> string.ascii_lowercase[:14:2]
'acegikm'

To do the urls, you could use something like this

[i + j for i, j in zip(list_of_urls, string.ascii_lowercase[:14])]

回答 1

假设这是一项家庭作业;-)-无需调用库等-它可能希望您将chr / ord与range()一起使用,如下所示:

for i in range(ord('a'), ord('n')+1):
    print chr(i),

对于其余的内容,只需要使用range()多一点

Assuming this is a homework ;-) – no need to summon libraries etc – it probably expect you to use range() with chr/ord, like so:

for i in range(ord('a'), ord('n')+1):
    print chr(i),

For the rest, just play a bit more with the range()


回答 2

提示:

import string
print string.ascii_lowercase

for i in xrange(0, 10, 2):
    print i

"hello{0}, world!".format('z')

Hints:

import string
print string.ascii_lowercase

and

for i in xrange(0, 10, 2):
    print i

and

"hello{0}, world!".format('z')

回答 3

for one in range(97,110):
    print chr(one)
for one in range(97,110):
    print chr(one)

回答 4

获取具有所需值的列表

small_letters = map(chr, range(ord('a'), ord('z')+1))
big_letters = map(chr, range(ord('A'), ord('Z')+1))
digits = map(chr, range(ord('0'), ord('9')+1))

要么

import string
string.letters
string.uppercase
string.digits

此解决方案使用ASCII表ord从一个字符获取ascii值,然后chr反之亦然。

应用您对列表的了解

>>> small_letters = map(chr, range(ord('a'), ord('z')+1))

>>> an = small_letters[0:(ord('n')-ord('a')+1)]
>>> print(" ".join(an))
a b c d e f g h i j k l m n

>>> print(" ".join(small_letters[0::2]))
a c e g i k m o q s u w y

>>> s = small_letters[0:(ord('n')-ord('a')+1):2]
>>> print(" ".join(s))
a c e g i k m

>>> urls = ["hello.com/", "hej.com/", "hallo.com/"]
>>> print([x + y for x, y in zip(urls, an)])
['hello.com/a', 'hej.com/b', 'hallo.com/c']

Get a list with the desired values

small_letters = map(chr, range(ord('a'), ord('z')+1))
big_letters = map(chr, range(ord('A'), ord('Z')+1))
digits = map(chr, range(ord('0'), ord('9')+1))

or

import string
string.letters
string.uppercase
string.digits

This solution uses the ASCII table. ord gets the ascii value from a character and chr vice versa.

Apply what you know about lists

>>> small_letters = map(chr, range(ord('a'), ord('z')+1))

>>> an = small_letters[0:(ord('n')-ord('a')+1)]
>>> print(" ".join(an))
a b c d e f g h i j k l m n

>>> print(" ".join(small_letters[0::2]))
a c e g i k m o q s u w y

>>> s = small_letters[0:(ord('n')-ord('a')+1):2]
>>> print(" ".join(s))
a c e g i k m

>>> urls = ["hello.com/", "hej.com/", "hallo.com/"]
>>> print([x + y for x, y in zip(urls, an)])
['hello.com/a', 'hej.com/b', 'hallo.com/c']

回答 5

import string
print list(string.ascii_lowercase)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
import string
print list(string.ascii_lowercase)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

回答 6

import string
print list(string.ascii_lowercase)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

for c in list(string.ascii_lowercase)[:5]:
    ...operation with the first 5 characters
import string
print list(string.ascii_lowercase)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

and

for c in list(string.ascii_lowercase)[:5]:
    ...operation with the first 5 characters

回答 7

myList = [chr(chNum) for chNum in list(range(ord('a'),ord('z')+1))]
print(myList)

输出量

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
myList = [chr(chNum) for chNum in list(range(ord('a'),ord('z')+1))]
print(myList)

Output

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

回答 8

#1)
print " ".join(map(chr, range(ord('a'),ord('n')+1)))

#2)
print " ".join(map(chr, range(ord('a'),ord('n')+1,2)))

#3)
urls = ["hello.com/", "hej.com/", "hallo.com/"]
an = map(chr, range(ord('a'),ord('n')+1))
print [ x + y for x,y in zip(urls, an)]
#1)
print " ".join(map(chr, range(ord('a'),ord('n')+1)))

#2)
print " ".join(map(chr, range(ord('a'),ord('n')+1,2)))

#3)
urls = ["hello.com/", "hej.com/", "hallo.com/"]
an = map(chr, range(ord('a'),ord('n')+1))
print [ x + y for x,y in zip(urls, an)]

回答 9

这个问题的答案很简单,只需列出一个名为ABC的列表,如下所示:

ABC = ['abcdefghijklmnopqrstuvwxyz']

每当需要引用它时,只需执行以下操作:

print ABC[0:9] #prints abcdefghij
print ABC       #prints abcdefghijklmnopqrstuvwxyz
for x in range(0,25):
    if x % 2 == 0:
        print ABC[x] #prints acegikmoqsuwy (all odd numbered letters)

也可以尝试这样来破坏您的设备:D

##Try this and call it AlphabetSoup.py:

ABC = ['abcdefghijklmnopqrstuvwxyz']


try:
    while True:
        for a in ABC:
            for b in ABC:
                for c in ABC:
                    for d in ABC:
                        for e in ABC:
                            for f in ABC:
                                print a, b, c, d, e, f, '    ',
except KeyboardInterrupt:
    pass

The answer to this question is simple, just make a list called ABC like so:

ABC = ['abcdefghijklmnopqrstuvwxyz']

And whenever you need to refer to it, just do:

print ABC[0:9] #prints abcdefghij
print ABC       #prints abcdefghijklmnopqrstuvwxyz
for x in range(0,25):
    if x % 2 == 0:
        print ABC[x] #prints acegikmoqsuwy (all odd numbered letters)

Also try this to break ur device :D

##Try this and call it AlphabetSoup.py:

ABC = ['abcdefghijklmnopqrstuvwxyz']


try:
    while True:
        for a in ABC:
            for b in ABC:
                for c in ABC:
                    for d in ABC:
                        for e in ABC:
                            for f in ABC:
                                print a, b, c, d, e, f, '    ',
except KeyboardInterrupt:
    pass

回答 10

尝试:

strng = ""
for i in range(97,123):
    strng = strng + chr(i)
print(strng)

Try:

strng = ""
for i in range(97,123):
    strng = strng + chr(i)
print(strng)

回答 11

这是您的第二个问题:string.lowercase[ord('a')-97:ord('n')-97:2]因为97==ord('a')-如果您想学习一点,您应该自己弄清楚其余的部分;-)

This is your 2nd question: string.lowercase[ord('a')-97:ord('n')-97:2] because 97==ord('a') — if you want to learn a bit you should figure out the rest yourself ;-)


回答 12

list(string.ascii_lowercase)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
list(string.ascii_lowercase)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

回答 13

我希望这有帮助:

import string

alphas = list(string.ascii_letters[:26])
for chr in alphas:
 print(chr)

I hope this helps:

import string

alphas = list(string.ascii_letters[:26])
for chr in alphas:
 print(chr)

回答 14

关于狼吞虎咽的答案。

邮编功能,充分说明,返回a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. [...]构造称为列表理解,很酷的功能!

About gnibbler’s answer.

Zip -function, full explanation, returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. [...] construct is called list comprehension, very cool feature!


回答 15

另一种方式

  import string
  pass

  aalist = list(string.ascii_lowercase)
  aaurls = ['alpha.com','bravo.com','chrly.com','delta.com',]
  iilen  =  aaurls.__len__()
  pass

  ans01 = "".join( (aalist[0:14]) )
  ans02 = "".join( (aalist[0:14:2]) )
  ans03 = "".join( "{vurl}/{vl}\n".format(vl=vjj[1],vurl=aaurls[vjj[0] % iilen]) for vjj in enumerate(aalist[0:14]) )
  pass

  print(ans01)
  print(ans02)
  print(ans03)
  pass

结果

abcdefghijklmn
acegikm
alpha.com/a
bravo.com/b
chrly.com/c
delta.com/d
alpha.com/e
bravo.com/f
chrly.com/g
delta.com/h
alpha.com/i
bravo.com/j
chrly.com/k
delta.com/l
alpha.com/m
bravo.com/n

这与其他回复有何不同

  • 遍历任意数量的基本网址
  • 循环浏览网址,直到我们用完所有字母后再停止
  • 使用enumerate结合列表理解和str.format

Another way to do it

  import string
  pass

  aalist = list(string.ascii_lowercase)
  aaurls = ['alpha.com','bravo.com','chrly.com','delta.com',]
  iilen  =  aaurls.__len__()
  pass

  ans01 = "".join( (aalist[0:14]) )
  ans02 = "".join( (aalist[0:14:2]) )
  ans03 = "".join( "{vurl}/{vl}\n".format(vl=vjj[1],vurl=aaurls[vjj[0] % iilen]) for vjj in enumerate(aalist[0:14]) )
  pass

  print(ans01)
  print(ans02)
  print(ans03)
  pass

Result

abcdefghijklmn
acegikm
alpha.com/a
bravo.com/b
chrly.com/c
delta.com/d
alpha.com/e
bravo.com/f
chrly.com/g
delta.com/h
alpha.com/i
bravo.com/j
chrly.com/k
delta.com/l
alpha.com/m
bravo.com/n

How this differs from the other replies

  • iterate over an arbitrary number of base urls
  • cycle through the urls and do not stop until we run out of letters
  • use enumerate in conjunction with list comprehension and str.format

Python字符串不是一成不变的吗?那么为什么a +“” + b有效呢?

问题:Python字符串不是一成不变的吗?那么为什么a +“” + b有效呢?

我的理解是Python字符串是不可变的。

我尝试了以下代码:

a = "Dog"
b = "eats"
c = "treats"

print a, b, c
# Dog eats treats

print a + " " + b + " " + c
# Dog eats treats

print a
# Dog

a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!

Python是否应该阻止分配?我可能错过了一些东西。

任何想法?

My understanding was that Python strings are immutable.

I tried the following code:

a = "Dog"
b = "eats"
c = "treats"

print a, b, c
# Dog eats treats

print a + " " + b + " " + c
# Dog eats treats

print a
# Dog

a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!

Shouldn’t Python have prevented the assignment? I am probably missing something.

Any idea?


回答 0

首先a指向字符串“ Dog”。然后,您将变量更改a为指向新的字符串“ Dog eats对待”。您实际上并未更改字符串“ Dog”。字符串是不可变的,变量可以指向它们想要的任何东西。

First a pointed to the string “Dog”. Then you changed the variable a to point at a new string “Dog eats treats”. You didn’t actually mutate the string “Dog”. Strings are immutable, variables can point at whatever they want.


回答 1

字符串对象本身是不可变的。

a指向字符串的变量是可变的。

考虑:

a = "Foo"
# a now points to "Foo"
b = a
# b points to the same "Foo" that a points to
a = a + a
# a points to the new string "FooFoo", but b still points to the old "Foo"

print a
print b
# Outputs:

# FooFoo
# Foo

# Observe that b hasn't changed, even though a has.

The string objects themselves are immutable.

The variable, a, which points to the string, is mutable.

Consider:

a = "Foo"
# a now points to "Foo"
b = a
# b points to the same "Foo" that a points to
a = a + a
# a points to the new string "FooFoo", but b still points to the old "Foo"

print a
print b
# Outputs:

# FooFoo
# Foo

# Observe that b hasn't changed, even though a has.

回答 2

变量a指向对象“ Dog”。最好将Python中的变量视为标签。您可以将标签移动到其他对象,这就是您更改为时的a = "dog"操作a = "dog eats treats"

但是,不变性是指对象,而不是标签。


如果你试图a[1] = 'z'"dog""dzg",你会得到错误:

TypeError: 'str' object does not support item assignment" 

因为字符串不支持项目分配,所以它们是不可变的。

The variable a is pointing at the object “Dog”. It’s best to think of the variable in Python as a tag. You can move the tag to different objects which is what you did when you changed a = "dog" to a = "dog eats treats".

However, immutability refers to the object, not the tag.


If you tried a[1] = 'z' to make "dog" into "dzg", you would get the error:

TypeError: 'str' object does not support item assignment" 

because strings don’t support item assignment, thus they are immutable.


回答 3

只有当我们能够更改存储位置中保存的值而不更改存储位置本身时,某些事情才是可变的。

诀窍是:如果发现更改前后的内存位置相同,则它是可变的。

例如,列表是可变的。怎么样?

>> a = ['hello']
>> id(a)
139767295067632

# Now let's modify
#1
>> a[0] = "hello new"
>> a
['hello new']
Now that we have changed "a", let's see the location of a
>> id(a)
139767295067632
so it is the same as before. So we mutated a. So list is mutable.

字符串是不可变的。我们如何证明呢?

> a = "hello"
> a[0]
'h'
# Now let's modify it
> a[0] = 'n'
----------------------------------------------------------------------

我们得到

TypeError:’str’对象不支持项目分配

因此,我们无法使字符串发生变异。这意味着字符串是不可变的。

在重新分配中,您将变量更改为指向新位置本身。在这里,您没有改变字符串,而是改变了变量本身。以下是您正在做什么。

>> a = "hello"
>> id(a)
139767308749440
>> a ="world"
>> id(a)
139767293625808

id重新分配之前和之后是不同的,因此这证明您实际上不是在变异,而是将变量指向新位置。这不是改变字符串,而是改变变量。

Something is mutable only when we are able to change the values held in the memory location without changing the memory location itself.

The trick is: If you find that the memory location before and after the change are the same, it is mutable.

For example, list is mutable. How?

>> a = ['hello']
>> id(a)
139767295067632

# Now let's modify
#1
>> a[0] = "hello new"
>> a
['hello new']
Now that we have changed "a", let's see the location of a
>> id(a)
139767295067632
so it is the same as before. So we mutated a. So list is mutable.

A string is immutable. How do we prove it?

> a = "hello"
> a[0]
'h'
# Now let's modify it
> a[0] = 'n'
----------------------------------------------------------------------

we get

TypeError: ‘str’ object does not support item assignment

So we failed mutating the string. It means a string is immutable.

In you reassigning, you change the variable to point to a new location itself. Here you have not mutated the string, but mutating the variable itself. The following is what you are doing.

>> a = "hello"
>> id(a)
139767308749440
>> a ="world"
>> id(a)
139767293625808

id before and after reassignment is different, so it this proves that you are actually not mutating, but pointing the variable to new location. Which is not mutating that string, but mutating that variable.


回答 4

变量只是指向对象的标签。该对象是不可变的,但是如果需要,可以使标签指向完全不同的对象。

A variable is just a label pointing to an object. The object is immutable, but you can make the label point to a completely different object if you want to.


回答 5

考虑:

>>> a='asdf'
>>> a.__repr__
<method-wrapper '__repr__' of str object at 0x1091aab90>
>>> a='asdf'
>>> a.__repr__
<method-wrapper '__repr__' of str object at 0x1091aab90>
>>> a='qwer'
>>> a.__repr__
<method-wrapper '__repr__' of str object at 0x109198490>

请注意,当我在变量中两次存储相同的值时,十六进制存储位置没有改变。当我存储其他值时,它确实发生了变化。该字符串是不可变的。不是因为狂热,而是因为您付出了在内存中创建新对象的性能损失。该变量a只是指向该内存地址的标签。可以更改它以指向任何内容。

Consider:

>>> a='asdf'
>>> a.__repr__
<method-wrapper '__repr__' of str object at 0x1091aab90>
>>> a='asdf'
>>> a.__repr__
<method-wrapper '__repr__' of str object at 0x1091aab90>
>>> a='qwer'
>>> a.__repr__
<method-wrapper '__repr__' of str object at 0x109198490>

Notice that the hex memory location did not change when I stored the same value in the variable twice. It did change when I stored a different value. The string is immutable. Not because of zealotry, but because you pay the performance penalty of creating a new object in memory. The variable a is just a label pointing to that memory address. It can be altered to point to anything.


回答 6

该语句a = a + " " + b + " " + c可以基于指针进行分解。

a + " "说给我a指向什么,不能更改,然后添加" "到我当前的工作集中。

记忆:

working_set = "Dog "
a = "Dog" 
b = "eats"
c = "treats"

+ b告诉我要b指向的内容,不能更改的内容,然后将其添加到当前工作集中。

记忆:

working_set = "Dog eats"
a = "Dog" 
b = "eats"
c = "treats"

+ " " + c说添加" "到当前集。然后给我c指出什么,不能更改,然后将其添加到当前工作集中。记忆:

working_set = "Dog eats treats"
a = "Dog" 
b = "eats"
c = "treats"

最后,a =说出将我的指针指向结果集。

记忆:

a = "Dog eats treats"
b = "eats"
c = "treats"

"Dog"被回收,因为没有更多的指针连接到它的内存块。我们从未修改过"Dog"驻留的内存部分,这就是不可变的意思。但是,我们可以更改指向该内存部分的标签(如果有)。

The statement a = a + " " + b + " " + c can be broken down based upon pointers.

a + " " says give me what a points to, which can’t be changed, and add " " to my current working set.

memory:

working_set = "Dog "
a = "Dog" 
b = "eats"
c = "treats"

+ b says give me what b points to, which can’t be changed, and add it to current working set.

memory:

working_set = "Dog eats"
a = "Dog" 
b = "eats"
c = "treats"

+ " " + c says add " " to the current set. Then give me what c points to, which can’t be changed, and add it to current working set. memory:

working_set = "Dog eats treats"
a = "Dog" 
b = "eats"
c = "treats"

Finally, a = says set my pointer to point to the resulting set.

memory:

a = "Dog eats treats"
b = "eats"
c = "treats"

"Dog" is reclaimed, because no more pointers connect to it’s chunk of memory. We never modified the memory section "Dog" resided in, which is what is meant by immutable. However, we can change which labels, if any, point to that section of memory.


回答 7

l = [1,2,3]
print id(l)
l.append(4)
print id(l) #object l is the same

a = "dog"
print id(a)
a = "cat"
print id(a) #object a is a new object, previous one is deleted
l = [1,2,3]
print id(l)
l.append(4)
print id(l) #object l is the same

a = "dog"
print id(a)
a = "cat"
print id(a) #object a is a new object, previous one is deleted

回答 8

数据与其关联的标签之间存在差异。例如当你做

a = "dog"

数据"dog"被创建并放置在标签下a。标签可以更改,但内存中的内容不会更改。执行"dog"完该操作后,数据仍将存在于内存中(直到垃圾回收器将其删除)

a = "cat"

a现在在您的程序中,^指向^,"cat"但是字符串"dog"没有改变。

There is a difference between data and the label it is associated with. For example when you do

a = "dog"

the data "dog" is created and put under the label a. The label can change but what is in the memory won’t. The data "dog" will still exist in memory (until the garbage collector deletes it) after you do

a = "cat"

In your programm a now ^points to^ "cat" but the string "dog" hasn’t changed.


回答 9

Python字符串是不可变的。但是,a它不是字符串:它是具有字符串值的变量。您不能更改字符串,但是可以将变量的值更改为新字符串。

Python strings are immutable. However, a is not a string: it is a variable with a string value. You can’t mutate the string, but can change what value of the variable to a new string.


回答 10

变量可以指向它们想要的任何位置。如果执行以下操作,将引发错误:

a = "dog"
print a                   #dog
a[1] = "g"                #ERROR!!!!!! STRINGS ARE IMMUTABLE

Variables can point to anywhere they want.. An error will be thrown if you do the following:

a = "dog"
print a                   #dog
a[1] = "g"                #ERROR!!!!!! STRINGS ARE IMMUTABLE

回答 11

Python字符串对象是不可变的。例:

>>> a = 'tanim'
>>> 'Address of a is:{}'.format(id(a))
'Address of a is:64281536'
>>> a = 'ahmed'
>>> 'Address of a is:{}'.format(id(a))
'Address of a is:64281600'

在这个例子中,我们可以看到当我们在a中分配不同的值时,它不会被修改,而是创建了一个新对象。
而且无法修改。例:

  >>> a[0] = 'c'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    **TypeError**: 'str' object does not support item assignment

发生错误。

Python string objects are immutable. Example:

>>> a = 'tanim'
>>> 'Address of a is:{}'.format(id(a))
'Address of a is:64281536'
>>> a = 'ahmed'
>>> 'Address of a is:{}'.format(id(a))
'Address of a is:64281600'

In this example we can see that when we assign different value in a it doesn’t modify.A new object is created.
And it can’t be modified. Example:

  >>> a[0] = 'c'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    **TypeError**: 'str' object does not support item assignment

A error occurs.


回答 12

‘mutable’意味着我们可以更改字符串的内容,’immutable’意味着我们不能添加额外的字符串。

点击查看照片证明

‘mutable’ means that we can change the content of the string, ‘immutable’ means that we can’t add an extra string.

click for photo proof


回答 13

>>> a = 'dogs'

>>> a.replace('dogs', 'dogs eat treats')

'dogs eat treats'

>>> print a

'dogs'

一成不变,不是吗?

变量更改部分已经讨论过。

>>> a = 'dogs'

>>> a.replace('dogs', 'dogs eat treats')

'dogs eat treats'

>>> print a

'dogs'

Immutable, isn’t it?!

The variable change part has already been discussed.


回答 14

考虑这个示例

 a = "Dog"
 b = "eats"
 c = "treats"
 print (a,b,c)
 #Dog eats treats
 d = a + " " + b + " " + c
 print (a)
 #Dog
 print (d)
 #Dog eats treats

我在博客中找到的更精确的解释之一是:

在Python中,(几乎)所有事物都是一个对象。在Python中我们通常称为“变量”的名称更恰当。同样,“赋值”实际上是名称与对象的绑定。每个绑定都有一个定义其可见性的范围,通常是名称起源的块。

例如:

some_guy = 'Fred'
# ...
some_guy = 'George'

当我们稍后说some_guy =’George’时,包含’Fred’的字符串对象不受影响。我们刚刚更改了名称some_guy的绑定。但是,我们没有更改’Fred’或’George’字符串对象。就我们而言,他们可能会无限期地生活下去。

链接到博客:https : //jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-nether/

Consider this addition to your example

 a = "Dog"
 b = "eats"
 c = "treats"
 print (a,b,c)
 #Dog eats treats
 d = a + " " + b + " " + c
 print (a)
 #Dog
 print (d)
 #Dog eats treats

One of the more precise explanations I found in a blog is:

In Python, (almost) everything is an object. What we commonly refer to as “variables” in Python are more properly called names. Likewise, “assignment” is really the binding of a name to an object. Each binding has a scope that defines its visibility, usually the block in which the name originates.

Eg:

some_guy = 'Fred'
# ...
some_guy = 'George'

When we later say some_guy = ‘George’, the string object containing ‘Fred’ is unaffected. We’ve just changed the binding of the name some_guy. We haven’t, however, changed either the ‘Fred’ or ‘George’ string objects. As far as we’re concerned, they may live on indefinitely.

Link to blog: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/


回答 15

在上述答案中添加更多内容。

id 变量的变化在重新分配时发生变化。

>>> a = 'initial_string'
>>> id(a)
139982120425648
>>> a = 'new_string'
>>> id(a)
139982120425776

这意味着我们已经将变量突变a为指向新的字符串。现在有两个 string(str)对象:

'initial_string'id= 139982120425648

'new_string'id= 139982120425776

考虑下面的代码:

>>> b = 'intitial_string'
>>> id(b)
139982120425648

现在,b指向'initial_string',并具有相同ida重新分配过的。

因此,'intial_string'尚未被突变。

Adding a bit more to above-mentioned answers.

id of a variable changes upon reassignment.

>>> a = 'initial_string'
>>> id(a)
139982120425648
>>> a = 'new_string'
>>> id(a)
139982120425776

Which means that we have mutated the variable a to point to a new string. Now there exist two string(str) objects:

'initial_string' with id = 139982120425648

and

'new_string' with id = 139982120425776

Consider the below code:

>>> b = 'intitial_string'
>>> id(b)
139982120425648

Now, b points to the 'initial_string' and has the same id as a had before reassignment.

Thus, the 'intial_string' has not been mutated.


回答 16

总结:

a = 3
b = a
a = 3+2
print b
# 5

不是一成不变的:

a = 'OOP'
b = a
a = 'p'+a
print b
# OOP

不可变:

a = [1,2,3]
b = range(len(a))
for i in range(len(a)):
    b[i] = a[i]+1

这是Python 3中的错误,因为它是不可变的。在Python 2中也不是错误,因为显然它不是不可变的。

Summarizing:

a = 3
b = a
a = 3+2
print b
# 5

Not immutable:

a = 'OOP'
b = a
a = 'p'+a
print b
# OOP

Immutable:

a = [1,2,3]
b = range(len(a))
for i in range(len(a)):
    b[i] = a[i]+1

This is an error in Python 3 because it is immutable. And not an error in Python 2 because clearly it is not immutable.


回答 17

内置函数id()以整数形式返回对象的标识。该整数通常对应于对象在内存中的位置。

\>>a='dog'
\>>print(id(a))

139831803293008

\>>a=a+'cat'
\>>print(id(a))

139831803293120

最初,“ a”存储在139831803293008的存储位置中,因为如果您尝试修改和重新分配该字符串对象,则在python中该对象是不可变的,该引用将被删除,并将成为新存储位置的指针(139831803293120)。

The built-in function id() returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory.

\>>a='dog'
\>>print(id(a))

139831803293008

\>>a=a+'cat'
\>>print(id(a))

139831803293120

Initially, ‘a’ is stored in 139831803293008 memory location, as the string object is immutable in python if you try to modify and reassign the reference will be removed and will be a pointer to a new memory location(139831803293120).


回答 18

a = 'dog'
address = id(a)
print(id(a))

a = a + 'cat'
print(id(a))      #Address changes

import ctypes
ctypes.cast(address, ctypes.py_object).value    #value at old address is intact
a = 'dog'
address = id(a)
print(id(a))

a = a + 'cat'
print(id(a))      #Address changes

import ctypes
ctypes.cast(address, ctypes.py_object).value    #value at old address is intact

回答 19

此图像给出了答案。请阅读。

在此处输入图片说明

This image gives the answer. Please read it.

enter image description here


回答 20

我们只是串联两个字符串值。我们永远不会改变(a)的值。刚才(a)表示另一个具有“ dogdog”值的存储块。因为在后端,一个变量永远不会代表两个内存块。串联前(a)的值为“ dog”。但是在那之后(a)代表“ dogdog”,因为现在(a)在后端代表中。具有“ dogdog”值的块。而“狗”是代表。直到(b)代表“狗”,“ b”和“ dog”才算作垃圾值。

困惑在于我们用相同的变量名来表示后端的内存块(包含数据或信息)。

We r just concatenate the two string values. We never change the value of (a). Just now (a) represent another memory block that has “dogdog” value. Because in the backend, one variable never represent two memory blocks at same time. The value of (a) before concatenation was “dog”. But after that (a) represent the “dogdog”, because now (a) in backend rep. the block that has “dogdog” value. And “dog” is rep. by (b) and “dog” isn’t counted as garbage value until (b) represent the “dog”.

The confusion is we represent the memory blocks(that contain data or info.) in backend with same variable name.


回答 21

您可以使numpy数组不变,并使用第一个元素:

numpyarrayname[0] = "write once"

然后:

numpyarrayname.setflags(write=False)

要么

numpyarrayname.flags.writeable = False

You can make a numpy array immutable and use the first element:

numpyarrayname[0] = "write once"

then:

numpyarrayname.setflags(write=False)

or

numpyarrayname.flags.writeable = False

如何在熊猫中更改日期时间格式

问题:如何在熊猫中更改日期时间格式

我的数据框有一个DOB列(示例格式1/1/2016),默认情况下该列会转换为dtype’object’熊猫:DOB object

使用将日期转换为日期格式df['DOB'] = pd.to_datetime(df['DOB']),日期将转换为:2016-01-26,日期dtype为:DOB datetime64[ns]

现在,我想将此日期格式转换为01/26/2016任何其他通用日期格式或。我该怎么做?

无论我尝试哪种方法,它始终以2016-01-26格式显示日期。

My dataframe has a DOB column (example format 1/1/2016) which by default gets converted to pandas dtype ‘object’: DOB object

Converting this to date format with df['DOB'] = pd.to_datetime(df['DOB']), the date gets converted to: 2016-01-26 and its dtype is: DOB datetime64[ns].

Now I want to convert this date format to 01/26/2016 or in any other general date formats. How do I do it?

Whatever the method I try, it always shows the date in 2016-01-26 format.


回答 0

dt.strftime如果需要转换datetime为其他格式,可以使用(但请注意,dtype列的则为objectstring)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

回答 1

更改格式但不更改类型:

df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

Changing the format but not changing the type:

df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

回答 2

下面的代码对我有用,而不是上一个-试试看!

df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')

The below code worked for me instead of the previous one – try it out !

df['DOB']=pd.to_datetime(df['DOB'].astype(str), format='%m/%d/%Y')

回答 3

与第一个答案相比,我建议先使用dt.strftime(),然后再使用pd.to_datetime()。这样,它将仍然导致datetime数据类型。

例如,

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '})
print(df.dtypes)

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print(df.dtypes)

df['DOB1'] = pd.to_datetime(df['DOB1'])
print(df.dtypes)

Compared to the first answer, I will recommend to use dt.strftime() first, then pd.to_datetime(). In this way, it will still result in the datetime data type.

For example,

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '})
print(df.dtypes)

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print(df.dtypes)

df['DOB1'] = pd.to_datetime(df['DOB1'])
print(df.dtypes)

回答 4

两者之间有区别

  • 数据帧单元的内容(二进制值)和
  • 它对我们(人类)的演示(展示)。

所以问题是:如何在不更改数据/数据类型本身的情况下达到我的数据的适当表示

答案是:

  • 如果您使用Jupyter笔记本显示数据,或者
  • 如果您想以HTML文件的形式进行演示(即使准备了许多多余的属性idclass属性来进行进一步的 CSS样式设置,则可以使用也可以不使用它们),

使用样式样式不会更改数据框列的数据/数据类型。

现在,我向您展示如何在Jupyter笔记本中找到它-有关HTML文件形式的演示文稿,请参阅问题末尾的注释。

我将假设您的列DOB 已经具有该类型datetime64(您已表明知道如何访问它)。我准备了一个简单的数据框(只有一列),向您展示了一些基本样式:

  • 没有样式:

       df
          DOB
0  2019-07-03
1  2019-08-03
2  2019-09-03
3  2019-10-03
  • 样式为mm/dd/yyyy

       df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
          DOB
0  07/03/2019
1  08/03/2019
2  09/03/2019
3  10/03/2019
  • 样式为dd-mm-yyyy

       df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")}) 
          DOB
0  03-07-2019
1  03-08-2019
2  03-09-2019
3  03-10-2019

小心!
返回的对象不是数据框-它是类的对象Styler,因此请勿将其分配回df

不要这样做:

df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})    # Don´t do this!

(每个数据框都可以通过其.style属性访问其Styler对象,我们更改了该df.style对象,而不是数据框本身。)


问题和解答:

  • 问: 为什么在Jupyter笔记本单元格中用作最后一条命令的Styler对象(或返回它的表达式)显示您的(样式化)表,而不显示Styler对象本身?

  • 答:因为每个Styler对象都有一个回调方法._repr_html_(),该方法返回用于呈现数据框的HTML代码(作为漂亮的HTML表)。

    Jupyter Notebook IDE 自动调用此方法以呈现具有此方法的对象。


注意:

您不需要Jupyter笔记本进行样式设置(即,在不更改数据/数据类型的情况下很好地输出数据框)。

render()如果您想使用HTML代码获取字符串(例如,用于将格式化的数据帧发布到Web上,或仅以HTML格式显示表格),则Styler对象也具有一种方法:

df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()

There is a difference between

  • the content of a dataframe cell (a binary value) and
  • its presentation (displaying it) for us, humans.

So the question is: How to reach the appropriate presentation of my datas without changing the data / data types themselves?

Here is the answer:

  • If you use the Jupyter notebook for displaying your dataframe, or
  • if you want to reach a presentation in the form of an HTML file (even with many prepared superfluous id and class attributes for further CSS styling — you may or you may not use them),

use styling. Styling don’t change data / data types of columns of your dataframe.

Now I show you how to reach it in the Jupyter notebook — for a presentation in the form of HTML file see the note near the end of the question.

I will suppose that your column DOB already has the type datetime64 (you shown that you know how to reach it). I prepared a simple dataframe (with only one column) to show you some basic styling:

  • Not styled:

       df
    
          DOB
0  2019-07-03
1  2019-08-03
2  2019-09-03
3  2019-10-03
  • Styling it as mm/dd/yyyy:

       df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
    
          DOB
0  07/03/2019
1  08/03/2019
2  09/03/2019
3  10/03/2019
  • Styling it as dd-mm-yyyy:

       df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")}) 
    
          DOB
0  03-07-2019
1  03-08-2019
2  03-09-2019
3  03-10-2019

Be careful!
The returning object is NOT a dataframe — it is an object of the class Styler, so don’t assign it back to df:

Don´t do this:

df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})    # Don´t do this!

(Every dataframe has its Styler object accessible by its .style property, and we changed this df.style object, not the dataframe itself.)


Questions and Answers:

  • Q: Why your Styler object (or an expression returning it) used as the last command in a Jupyter notebook cell displays your (styled) table, and not the Styler object itself?

  • A: Because every Styler object has a callback method ._repr_html_() which returns an HTML code for rendering your dataframe (as a nice HTML table).

    Jupyter Notebook IDE calls this method automatically to render objects which have it.


Note:

You don’t need the Jupyter notebook for styling (i.e. for nice outputting a dataframe without changing its data / data types).

A Styler object has a method render(), too, if you want to obtain a string with the HTML code (e.g. for publishing your formatted dataframe to the Web, or simply present your table in the HTML format):

df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()

回答 5

下面的代码更改为“ datetime”类型,并以给定的格式字符串格式化。效果很好!

df['DOB']=pd.to_datetime(df['DOB'].dt.strftime('%m/%d/%Y'))

Below code changes to ‘datetime’ type and also formats in the given format string. Works well!

df['DOB']=pd.to_datetime(df['DOB'].dt.strftime('%m/%d/%Y'))

回答 6

您可以尝试将日期格式转换为DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)

You can try this it’ll convert the date format to DD-MM-YYYY:

df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)

什么是Python?什么是“爆炸”?

问题:什么是Python?什么是“爆炸”?

我有一个存储在变量中的字符串myvar = "Rajasekar SP"。我想像explode在PHP中那样使用定界符将其拆分。

Python中的等效项是什么?

I had a string which is stored in a variable myvar = "Rajasekar SP". I want to split it with delimiter like we do using explode in PHP.

What is the equivalent in Python?


回答 0

选择您需要的一个:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.splitstr.partition

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition


回答 1

php中explode的替代方法是split

第一个参数是定界符,第二个参数是最大分割数。返回的部分不包含定界符(可能最后一个部分除外)。当定界符为“无”时,将匹配所有空格。这是默认值。

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']